全局异常处理类
package main.java.com.example.demo.exceptionHandler; import com.example.demo.exceptionHandler.MyException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @ControllerAdvice//定义统一的一场处理类 public class GlobalException { @ExceptionHandler(value = MyException.class) @ResponseBody public Map<String, String> jsonErrorHandler(HttpServletRequest request, MyException e) { Map<String, String> resultMap = new HashMap<>(); resultMap.put("status", e.getCode()); resultMap.put("msg", e.getMessage()); return resultMap; } @ExceptionHandler(value = MyException.class) public ModelAndView defaultErrorHandler(HttpServletRequest request, MyException e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception",e); mv.addObject("url",request.getRequestURL()); mv.setViewName("error");//定义默认的视图 return mv; } }
package com.example.demo.exceptionHandler; public class MyException extends Exception { private String code; public MyException(String message) { super(message); } public MyException(String message, String code) { super(message); this.code = code; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }