摘要
SpringBoot全局异常处理对象,这里只是一个简单的用ControllerAdvice完成的实现方式,实现的是对所有在服务器捕捉到的异常进行全局的处理,返回的是ModelAndView对象
说明
使用ControllerAdvice,ExceptionHandler等注解去使用
代码
在SpringBoot中的代码
package com.bothsavage.forum_study.advice;import com.alibaba.fastjson.JSON;import com.bothsavage.forum_study.dto.ResultDTO;import com.bothsavage.forum_study.exception.CustomizeErrorCode;import com.bothsavage.forum_study.exception.CustomizeException;import lombok.extern.slf4j.Slf4j;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;/*** 全局异常处理对象*/@ControllerAdvice@Slf4jpublic class CustomizeExceptionHandler {@ExceptionHandler(Exception.class)ModelAndView handle(Throwable e, Model model, HttpServletRequest request, HttpServletResponse response) {String contentType = request.getContentType();if ("application/json".equals(contentType)) {ResultDTO resultDTO;// 返回 JSONif (e instanceof CustomizeException) {resultDTO = ResultDTO.errorOf((CustomizeException) e);} else {log.error("handle error", e);resultDTO = ResultDTO.errorOf(CustomizeErrorCode.SYS_ERROR);}try {response.setContentType("application/json");response.setStatus(200);response.setCharacterEncoding("utf-8");PrintWriter writer = response.getWriter();writer.write(JSON.toJSONString(resultDTO));writer.close();} catch (IOException ioe) {}return null;} else {// 错误页面跳转if (e instanceof CustomizeException) {model.addAttribute("message", e.getMessage());} else {log.error("handle error", e);model.addAttribute("message", CustomizeErrorCode.SYS_ERROR.getMessage());}return new ModelAndView("error");}}}
注意
这里就是一个简单的demo,目的是为了知道有这个东西,能马上复制代码拿过来用
