java全局異常捕捉處理


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

    /**
     * 全局異常捕捉處理
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public DataResponse<Boolean> errorHandler(HttpServletRequest req, Exception ex) {
        Map map = new HashMap();
        map.put("code", 500);
        map.put("ex",ex);
        map.put("message", ex.getMessage());
        map.put("url", req.getRequestURL());
        log.error("發生異常:{}",JSON.toJSONString(map));
        return DataResponse.builderFailed(ex.getMessage());
    }

}

  

 

 

@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 攔截什么異常類 后面的是自定義異常類


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM