SpringBoot(一)-- 统一异常处理

一、自定义异常

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;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_46218511/article/details/106895799