优化了下项目的异常处理,直接上代码!
/**
* 全局异常处理器
* @author xx
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
public Map<String, Object> exceptionHandler(Exception e) {
log.info("捕获全局异常:" + e.getMessage());
log.info(e.toString());
Map<String, Object> res = new HashMap<>();
res.put("code", 5001);
res.put("message", e.getMessage());
//res.put("cause",e.getCause().toString());
res.put("stackTrace[0]",e.getStackTrace()[0]);
return res;
}
}
/**
* 自定义异常
* @author xx
*/
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
private Integer code;
private String message;
public CustomException(String message) {
this.message = message;
}
public CustomException(Integer code) {
this.code = code;
}
public CustomException(String message, Integer code) {
this.message = message;
this.code = code;
}
public CustomException(Integer code, String message, Throwable e) {
this.code = code;
this.message = message;
this.code = code;
}
public CustomException(Integer code,String message) {
Map<String,Object> res = new HashMap<>();
this.code = code;
this.message = message;
}
public CustomException(String message, Throwable e) {
super(message, e);
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public Integer getCode() {
return code;
}
}
@RestController
public class TestController {
@GetMapping("test")
public String test() {
if (true) {
throw new CustomException("1111");
}
//int a = 1/0;
return "hello";
}
}
@RestController
public class TestController {
@GetMapping("test")
public String test() {
//if (true) {
// throw new CustomException("1111");
//}
int a = 1/0;
return "hello";
}
}
以上基本满足项目需要,暂时先这样处理。
腾云先锋(TDP,Tencent Cloud Developer Pioneer)是腾讯云GTS官方组建并运营的技术开发者群体。这里有最专业的开发者&客户,能与产品人员亲密接触,专有的问题&需求反馈渠道,有一群志同道合的兄弟姐妹。来加入属于我们开发者的社群吧!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。