优雅统一处理异常

优雅统一处理异常

源码地址:
https://gitee.com/liuerchong/news-artical/

自定义异常类

在artical-clnews项目下新建自定义异常类

package com.liu.news.artical.clnews.exception;

import lombok.Data;

/**
 * @author lx
 * @version 1.0
 * @description: TODO
 * @date 2021/7/20 13:33
 */
@Data
public class CustomException extends RuntimeException{

    public CustomException(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private String code;
    private String msg;

}

自定义异常处理方法

package com.liu.news.artical.clnews.exception;

import com.liu.news.common.utils.R;
import org.apache.http.HttpEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lx
 * @version 1.0
 * @description: TODO
 * @date 2021/7/20 13:34
 */
@ControllerAdvice
public class CustomControllerAdvice {

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public R errorHandler(Exception ex) {
       /* Map map = new HashMap();
        map.put("code", 100);
        map.put("msg", ex.getMessage());
        return map;*/
        return  R.failed(null,500,ex.getMessage());
       //return R.failed(ex.getMessage());
    }

    /**
     * 拦截捕捉自定义异常 MyException.class
     * @param ex
     * @return
     */
    @ResponseBody
   @ExceptionHandler(value = CustomException.class)
    public R myErrorHandler(CustomException ex) {
        /*Map map = new HashMap();
        map.put("code", ex.getCode());
        map.put("msg", ex.getMsg());
        return map;*/
       // return R.failed(ex.getMessage());
        return  R.failed(null,500,ex.getMessage());
    }
}

自定义异常测试

@GetMapping("/hello")
public R hello() throws InterruptedException {

    int i = 1/0;
    //TimeUnit.MINUTES.sleep(3);
    return R.ok("hello world");
   // return "hello world";
}

启动服务

{“code”:500,“msg”:"/ by zero",“data”:null}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值