java 全局異常攔截

代碼如下

@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class GlobalExceptionInterceptor {

    /**
     * 捕獲自定義異常,返回json信息
     */
    @ExceptionHandler({MamchargeException.class})
    @ResponseBody
    public ResultVO errorHandle(MamchargeException e) throws Exception {
        return new ResultVO(null,e.getErrorCode(),e.getMsg());
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public ResultVO errorHandle(Exception e) throws Exception {
        log.error("系統出錯:",e);
        return ResultVO.isFail();
    }
}

RestControllerAdvice 註解表示攔截那一層

ExceptionHandler 攔截什麼異常類 後面的是自定義異常類

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章