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