SpringBoot 全局异常拦截和日志配置

SpringBoot 全局异常拦截和日志配置

作用:SpringBoot中不用关心异常,不用显示的进行try/catch,代码美观,正解

作用域:所有注解了@RequestMapping的控制器的方法上,说白了就是Controller

扩展:可以加到类上,也可以加到类的方法上

关于代码的几点说明:

代码中的@Data注解是应用了Lombok,需要的话导入下,也可以删除注解,自己生成get/set和构造方法
json格式化工具用的是fastjson
异常中加入了写日志,稍后会把日志的配置代码一并贴出来

全局异常配置类

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
 
    private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";
    private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
 
    //运行时异常
    @ExceptionHandler(RuntimeException.class)
    public String runtimeExceptionHandler(RuntimeException ex) {
        log.error(resultFormat(1, ex));
        return resultFormat(1, ex);
    }
 
    //空指针异常
    @ExceptionHandler(NullPointerException.class)
    public String nullPointerExceptionHandler(NullPointerException ex) {
        System.err.println("NullPointerException:");
        log.error(resultFormat(2, ex));
        return resultFormat(2, ex);
    }
 
    //类型转换异常
    @ExceptionHandler(ClassCastException.class)
    public String classCastExceptionHandler(ClassCastException ex) {
        log.error(resultFormat(3, ex));
        return resultFormat(3, ex);
    }
 
    //IO异常
    @ExceptionHandler(IOException.class)
    public String iOExceptionHandler(IOException ex) {
        log.error(resultFormat(4, ex));
        return resultFormat(4, ex);
    }
 
    //未知方法异常
    @ExceptionHandler(NoSuchMethodException.class)
    public String noSuchMethodExceptionHandler(NoSuchMethodException ex) {
        log.error(resultFormat(5, ex));
        return resultFormat(5, ex);
    }
 
    //数组越界异常
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
        log.error(resultFormat(6, ex));
        return resultFormat(6, ex);
    }
 
    //400错误
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public String requestNotReadable(HttpMessageNotReadableException ex) {
        log.error(resultFormat(7, ex));
        System.out.println("400..requestNotReadable");
        return resultFormat(7, ex);
    }
 
    //400错误
    @ExceptionHandler({TypeMismatchException.class})
    public String requestTypeMismatch(TypeMismatchException ex) {
        log.error(resultFormat(8, ex));
        System.out.println("400..TypeMismatchException");
        return resultFormat(8, ex);
    }
 
    //400错误
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public String requestMissingServletRequest(MissingServletRequestParameterException ex) {
        log.error(resultFormat(9, ex));
        System.out.println("400..MissingServletRequest");
        return resultFormat(9, ex);
    }
 
    //405错误
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public String request405(HttpRequestMethodNotSupportedException ex) {
        log.error(resultFormat(10, ex));
        return resultFormat(10, ex);
    }
 
    //406错误
    @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
    public String request406(HttpMediaTypeNotAcceptableException ex) {
        log.error(resultFormat(11, ex));
        System.out.println("406...");
        return resultFormat(11, ex);
    }
 
    //500错误
    @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
    public String server500(RuntimeException ex) {
        log.error(resultFormat(12, ex));
        System.out.println("500...");
        return resultFormat(12, ex);
    }
 
    //栈溢出
    @ExceptionHandler({StackOverflowError.class})
    public String requestStackOverflow(StackOverflowError ex) {
        log.error(resultFormat(13, ex));
        return resultFormat(13, ex);
    }
 
    //除数不能为0
    @ExceptionHandler({ArithmeticException.class})
    public String arithmeticException(ArithmeticException ex) {
        log.error(resultFormat(13, ex));
        return resultFormat(13, ex);
    }
 
 
    //其他错误
    @ExceptionHandler({Exception.class})
    public String exception(Exception ex) {
        log.error(resultFormat(14, ex));
        return resultFormat(14, ex);
    }
 
    private  String resultFormat(Integer code, T ex) {
        log.error(JsonResult.failed(code, ex.getMessage()));
        ex.printStackTrace();
        log.error(String.format(logExceptionFormat, code, ex.getMessage()));
        return JsonResult.failed(code, ex.getMessage());
    }
 
}

JSON格式化输出

@Data
public class JsonResult implements Serializable {
 
    private int code;   //返回码 非0即失败
    private String msg; //消息提示
    private Map data; //返回的数据
 
    public JsonResult() {
    }
 
    ;
 
    public JsonResult(int code, String msg, Map data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
 
    public static String success() {
        return success(new HashMap(0));
    }
 
    public static String success(Map data) {
        return JSON.toJSONString(new JsonResult(0, "解析成功", data));
    }
 
    public static String failed() {
        return failed("解析失败");
    }
 
    public static String failed(String msg) {
        return failed(-1, msg);
    }
 
    public static String failed(int code, String msg) {
        return JSON.toJSONString(new JsonResult(code, msg, new HashMap(0)));
    }
 
}

controller测试代码

    @RequestMapping("/zero")
    @ResponseBody
    public String zero() {
        System.err.println("Controller测试");
        String info = "除0异常";
        int a = 1 / 0;
        return info;
    }

日志输出

Capture Exception By GlobalExceptionHandler: Code: 13 Detail: / by zero

日志的配置:application.properties

#log
logging.config=classpath:logback.xml
logging.path=E:/log
Logback.xml配置文件



    
    
    
    
        
            
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
        
    
    
    
        
            
            ${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log
            
            30
        
        
            
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
        
        
        
            10MB
        
    
    
    
    
    
    
    
 
    
    
    
    
    
 
    
    
        
        
    
    
    
    
    
    
    
    
    
    
    
    
    
    


作者:清水贤人
来源:CSDN
原文:https://blog.csdn.net/wjsshhx/article/details/86175486
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(java,java,springboot,全局异常拦截,日志配置)