优雅统一处理异常
源码地址:
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}