一、自定义异常
public class SystemException extends RuntimeException{
private String code;//状态码
public SystemException(String message, String code) {
super(message);
this.code = code;
}
public String getCode() {
return code;
}
}
二、统一异常处理类
@ControllerAdvice
public class GloablExceptionHandler {
//其他异常
@ResponseBody
@ExceptionHandler(Exception.class)
public Object handleException(Exception e) {
// 记录错误信息
String msg = e.getMessage();
if (msg == null || msg.equals("")) {
msg = "服务器出错";
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", msg);
return jsonObject;
}
//自定义异常
@ResponseBody
@ExceptionHandler(SystemException.class)
public Object sysException(SystemException e) {
// 记录错误信息
String msg = e.getMessage();
if (msg == null || msg.equals("")) {
msg = "服务器出错";
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", msg);
return jsonObject;
}
}