全部try catch处理,全局异常

是否在写代码的时候遇到过这样一种情况,蛮项目写的都是try catch,尤其是controller,本来就是一个简单的sellect,写了贼多的代码.

是不是这个时候就想要一个全局的异常处理的机制来处理,是不是第一灵感就会想到切面.

下面来记录下全局异常捕获的方法

package com.example.demo11;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author :szy
 * @title: HelloController
 * @projectName demo11
 * @description: TODO
 * @date 2020/10/30-11:40
 */
@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello(){

        String val ="10-1";
        //异常
        Integer.valueOf(val);

        return "hello world";
    }
}

异常捕获代码

package com.example.demo11;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author :szy
 * @title: UnifiedExceptionHandler
 * @projectName demo11
 * @description: TODO
 * @date 2020/10/30-11:50
 */
@Component
@ControllerAdvice
public class UnifiedExceptionHandler {

    private Logger log = LoggerFactory.getLogger(UnifiedExceptionHandler.class);

    /**
     * 自定义异常
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = NumberFormatException.class)
    @ResponseBody
    public String handleNumberFormatException(NumberFormatException e) {
        log.error(e.getMessage(), e);
        return "转换错误";
    }



    /**
     * 全局异常处理
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String handleBaseException(Exception e) {
        log.error(e.getMessage(), e);
        return "error 0000";
    }

}

运行的结果:

原文地址:https://www.cnblogs.com/sunxun/p/13901420.html