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
  ### 关闭资源映射
  web:
    resources:
      add-mappings: false
上一篇:asp.net MVC控制器中返回JSON格式的数据时提示下载


下一篇:【SpringMVC】RestFul