一、新建一個統一異常處理類;如下
@ControllerAdvice
public class ExceptionHandlerConfig {
/**
* 全局異常捕捉處理
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 100);
map.put("msg",ex.getMessage());
return map;
}
}
@ControllerAdvice是一個@Component,用於定義@ExceptionHandler,@InitBinder和@ModelAttribute方法,適用於所有使用@RequestMapping方法。
@ResponseBody 返回json數據
@ExceptionHandler(Exception.class) springboot統一異常處理注解;
二、如果是自定義異常的話,查看debug信息,發現自己輸出的異常信息在ThrowableException中的detailMessage屬性,
使用
ex.getCause().getMessage() 方法可以獲取該屬性;
完整代碼;
@ControllerAdvice
public class ExceptionHandlerConfig {
/**
* 全局異常捕捉處理
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 100);
if(ex.getCause().getMessage().equals("AuthorityFail")){
map.put("msg","你沒有權限,請聯系管理員");
}else {
map.put("msg",ex.getMessage());
}
return map;
}
}
————————————————
版權聲明:本文為CSDN博主「蘇夏」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_31807569/article/details/88672156