崛起于Springboot2.0.X之统一异常处理(51)

      序言:很多时候都要写try catch,所以为了减少代码把异常处理单独拿出来,做一个全局处理,一般公司都是自定义异常为主,今天写一个默认异常和自定义异常的配置,很简单,五分钟就能掌握,而且代码全面,属于企业用法。

1、pom依赖


    org.springframework.boot
    spring-boot-starter-web



    org.projectlombok
    lombok
    true

2、application.properties

server.port=8082

3、响应信息

@Data
@AllArgsConstructor
public class Result {
    private boolean success;
    private String code;
    private String message;
    private Object data;
    public Result() {
        this.success = true;
        this.code = "200";
    }
}

4、自定义异常

@Data
@NoArgsConstructor
@AllArgsConstructor
public class MyException extends RuntimeException {

    /**
     * 异常状态码
     */
    private String code;

    /**
     * 异常信息
     */
    private String message;

    /**
     * 发生的方法
     */
    private String method;

    /**
     * 描述
     */
    private String desc;
}

5、全局一场配置

@Controller
@ControllerAdvice
public class MyControllerAdvice {

    /**
     * 全局异常处理
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(Exception e){
        Result result = new Result();
        result.setCode("201");
        result.setSuccess(false);
        result.setMessage(e.getMessage());
        //异常业务逻辑处理(日志记录或者其他存储)

        return result;
    }

    /**
     * 自定义异常
     */
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public Result exceptionHandler(MyException e) {
        Result result = new Result();
        result.setCode(e.getCode());
        result.setMessage(e.getMessage());
        result.setSuccess(false);
        result.setData(e.getDesc());
        return result;
    }
}

6、Controller层

@Controller
public class FirstController {
    
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    @ResponseBody
    public Result test1() throws Exception {
        throw new Exception("dnwbid");
    }

    @RequestMapping(value = "/test2",method = RequestMethod.GET)
    @ResponseBody
    public Result test2() {
        throw new MyException("201","测试异常保持","testOne","desc");
    }
}

7、测试

        http://localhost:8082/test1

崛起于Springboot2.0.X之统一异常处理(51)_第1张图片

        http://localhost:8082/test2崛起于Springboot2.0.X之统一异常处理(51)_第2张图片

转载于:https://my.oschina.net/mdxlcj/blog/3101931

你可能感兴趣的:(java)