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
posted @ 2020-12-21 18:56  rm-rf*  阅读(615)  评论(0编辑  收藏  举报