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

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

1、pom依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
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

28b53f2e54e06df2082eedd421b53cfc768.jpg

        http://localhost:8082/test20272f1cd37fc97e950dc29ae92c7ed47bcc.jpg

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值