Restful API 定制404返回結果


配置全局advice

@RestControllerAdvice
public class GlobalAdvice {

    /**
     * 處理404,記得配置yaml
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public BaseCommonResult<String>  handlerNoFoundException(Exception e)
    {
        return BaseCommonResult.failed(ResultCode.PageNotFound);
    }
}

配置application.yaml

注意,關閉資源映射會導致swagger失效,要在MvcConfig中放行swagger資源

spring:
  mvc:
    ### 讓mvc直接拋出異常,在全局異常類,捕獲404 異常的類 NoHandlerFoundException.class
    throw-exception-if-no-handler-found: true
  ### 關閉資源映射
  resources:
    add-mappings: false


免責聲明!

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



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