天天看點

@ControllerAdvice和@ExceptionHandler實作全局捕獲異常

##全局捕獲異常:相當于整個web請求項目全局捕獲異常,一般對整個controller層抛出的異常做統一處理。

##異常處理有兩種方式:1、捕獲傳回json格式;2、捕獲傳回頁面的

@ControllerAdvice(basePackages= {"com.demo"})
public class GlobalCatchErrorController {
    

    1、捕獲傳回json格式
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Map<String,String> globalCatchErrorJson() {
        Map<String, String> errorMap = new HashMap<String,String>();
        errorMap.put("returnCode", "2999");
        errorMap.put("returnMessage", "系統繁忙,請稍後重試!");
        return errorMap;
    }


    2、捕獲傳回頁面的
    @ExceptionHandler(Exception.class)
    public String globalCatchErrorView() {
        return "error";
    }
}
           

繼續閱讀