1.定义异常处理类
public class MyException extends Exception{
private static final long serialVersionUID = -5519743897907627214L;
public MyException(String message) {
super(message);
}
}
public class MyRuntimeException extends RuntimeException {
private static final long serialVersionUID = -6925278824391495117L;
public MyRuntimeException(String message) {
super(message);
}
}
2.异常处理器
@ControllerAdvice
@ResponseBody
public class MyExceptionHandler {
@ExceptionHandler(MyException.class)
@ResponseBody
public Map<String, Object> handlerMyException(MyException ex) {
Map<String,Object> result = new HashMap<>();
result.put("message", ex.getMessage());
result.put("code", 300);
return result;
}
@ExceptionHandler(MyRuntimeException.class)
@ResponseBody
public Map<String, Object> handlerMyRuntimeException(MyRuntimeException ex) {
Map<String,Object> result = new HashMap<>();
result.put("message", ex.getMessage());
result.put("code", 300);
return result;
}
}
3.在抛出异常时打印信息为
{
"code":300,
"message":"自定义异常信息"
}
@ControllerAdvice
@ResponseBody
没有加这个注解返回信息是
{
"timestamp": "2018-12-20 15:19:46",
"status": 500,
"error": "Internal Server Error",
"message": "Request processing failed; nested exception is **Exception: 用户未登录或会话过期",
"path": "/"
}
原文参考:https://blog.youkuaiyun.com/smollsnail/article/details/79143007