Spring MVC 處理異常的3種方式

三種方式

  • @ExceptionHandler標(biāo)注的方法被定義為處理指定類型異常;
  • @ResponseStatus標(biāo)注的方法執(zhí)行,會修改響應(yīng)頭中的狀態(tài)碼;
  • Spring會把@ControllerAdvice的類內(nèi)部使用@ExceptionHandler方法應(yīng)用到所有的 @RequestMapping注解的方法上

ExceptionHandler注解方式

注:@ExceptionHandler標(biāo)注的方法,方法簽名靈活、多變。被@ResponseStatus注解的方法將會修改相應(yīng)狀態(tài)碼,而使用@ResponseBody可以返回json格式的數(shù)據(jù),再供前端處理

 /**
     * 用戶注冊
     * @param user
     * @return
     */
    @GetMapping("/register")
    public String register(User user){
        Assert.notNull(null,"request is null");
        userService.register(user);
        return "success";
    }

    /**
     * 當(dāng)前控制器的異常處理
     */
//    @ResponseStatus(value = HttpStatus.BAD_REQUEST,reason = "參數(shù)異常")
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public String exceptionHandler(RuntimeException e){
        // 不做任何事或者可以做任何事
        return e.getMessage();
    }

全局異常處理

@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public GlobalExceptionHandler() {
    }

    @ExceptionHandler({Exception.class})
    public String defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        log.error("---BaseException Handler---Host {} invokes url {} ERROR: ", new Object[]{req.getRemoteHost(), req.getRequestURL(), e});
        return JsonResUtil.respJson(CodeEnum.SERVICE_ERROR);
    }

    @ExceptionHandler({AppException.class})
    public String jsonErrorHandle(HttpServletRequest req, AppException e) {
        log.warn("---BaseException Handler---Host {} invokes url {}  ", req.getRemoteHost(), req.getRequestURL());
        return JsonResUtil.respJson(e.getCode(), e.getMessage());
    }
}

文章參考:
http://www.cnblogs.com/zhaohongtian/p/6807100.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容