首页 > 其他分享 >Spring REST 接口自定义404不能捕获NoHandlerFoundException问题

Spring REST 接口自定义404不能捕获NoHandlerFoundException问题

时间:2023-06-27 11:15:24浏览次数:49  
标签:HashMap 自定义 Spring add NoHandlerFoundException spring response resources

Spring REST 接口自定义404以及解决不能捕获NoHandlerFoundException问题  

一、自定义404响应内容

版本说明:Spring Boot 2.0.1.RELEASE

REST风格默认PostMan请求的404响应如下:

{
    "timestamp": "2018-06-07T05:23:27.196+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/shopping/123/TEST"
}

 

如果不想返回此内容,可以做如下配置:

步骤一:

application.properties文件中添加如下两句:

#没有绑定的url直接抛出错误
spring.mvc.throw-exception-if-no-handler-found=true
#不为静态文件建立映射
spring.resources.add-mappings=false

添加以上配置后,404时DispatcherServlet会抛出NoHandlerFoundException,注意spring.resources.add-mappings 在当前版本下需要设置为false,否则不会抛出异常。

mappedHandler = getHandler(processedRequest);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
    noHandlerFound(processedRequest, response);
    return;
}

只有第一句代码找不到对应该请求的处理器时,才会进入下面的noHandler方法去抛出NoHandlerFoundException异常。通过测试发现,springboot的WebMvcAutoConfiguration会默认配置如下资源映射:

/映射到/static(或/public、/resources、/META-INF/resources) /webjars/ 映射到classpath:/META-INF/resources/webjars/ /**/favicon.ico映射favicon.ico文件.

配置如下属性,NoHandlerFoundException异常就能被@ControllerAdvice捕获了

#不存在的url直接抛出异常
spring.mvc.throw-exception-if-no-handler-found=true
#不添加静态资源映射
spring.resources.add-mappings=false
#指定静态资源路径
spring.mvc.static-path-pattern=/statics/**
#浏览器访问时Remove Whitelabel Error Page
server.error.whitelabel.enabled=false

步骤二:

全局异常捕获通过@ExceptionHandler(NoHandlerFoundException.class)

@RestControllerAdvice
public class ExceptionResolver {

    @ExceptionHandler(Exception.class)
    public HashMap<String, String> handleException(HttpServletRequest request, Exception e) {
        HashMap<String, String> response = new HashMap<>();
        response.put("message", e.getMessage());
        return response;
    }

    @ExceptionHandler(MissingPathVariableException.class)
    public HashMap<String, String> handleMissingPathVariableException(HttpServletRequest request, MissingPathVariableException e) {
        HashMap<String, String> response = new HashMap<>();
        response.put("message", "Required path variable is missing in this request. Please add it to your request.");
        return response;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public HashMap<String, String> handleNotFoundResourceException(HttpServletRequest request, NoHandlerFoundException e) {
        HashMap<String, String> response = new HashMap<>();
        response.put("message", "Requested resource wasn't found on the server");
        return response;
    }
}

 

二、注意事项

网上搜基本上都是说只需设置spring.mvc.throw-exception-if-no-handler-found=true即可,但设置后依然无效!

或者是需要设置spring.resources.add-mappings=false,但设置后依然无效!

通过看DispatcherServlet源码才发现,Srpingboot的版本不同spring.resources.add-mappings配置存在差异。

高版本比如Srping boot 2.7 要使用spring.web.resources.add-mappings=false才能生效。

另外全局异常类上要注意@RestControllerAdvice(basePackages ) 不要指定basePackages

 

参考文档:https://skryvets.com/blog/2018/12/27/enhance-exception-handling-when-building-restful-api-with-spring-boot/

标签:HashMap,自定义,Spring,add,NoHandlerFoundException,spring,response,resources
From: https://www.cnblogs.com/terrylin/p/17508131.html

相关文章

  • Gradle Spring Boot
    新建项目直接在线新建: https://start.spring.io/然后对比本地的区别,修改build.gradle.kts编码问题参考: Gradle项目中文乱码的解决办法打包问题参考springboot插件官网: https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/htmlsingle/build.grad......
  • 分布式任务elasticjob整合springboot本地多服务启动(附源码)
    Elastic-Job是一个分布式调度的解决方案,由当当网开源,它由两个相互独立的子项目Elastic-Job-Lite和ElasticJob-Cloud组成,使用Elastic-Job可以快速实现分布式任务调度。Elastic-Job的github地址:https://github.com/elasticjob功能列表:分布式调度协调在分布式环境中,任务能够按指......
  • SpringBoot假死,十万火急,怎么救火?
    文章很长,且持续更新,建议收藏起来,慢慢读!疯狂创客圈总目录博客园版为您奉上珍贵的学习资源:免费赠送:《尼恩Java面试宝典》持续更新+史上最全+面试必备2000页+面试必备+大厂必备+涨薪必备免费赠送:《尼恩技术圣经+高并发系列PDF》,帮你实现技术自由,完成职业升级,薪......
  • springboot学习-1
    最终目录结构:pom.xml:<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://mav......
  • Android自定义控件
    继承现有控件类publicclassLeftButtonBarextendsLinearLayout{//默认实现的构造函数beginpublicLeftButtonBar(Contextcontext){super(context);}publicLeftButtonBar(Contextcontext,@NullableAttributeSetattrs){supe......
  • 前端Vue自定义加载中loading加载结束end组件 可用于分页展示 页面加载请求
    前端Vue自定义加载中loading加载结束end组件可用于分页展示页面加载请求,请访问uni-app插件市场地址:https://ext.dcloud.net.cn/plugin?id=13219效果图如下:实现代码如下:cc-paging使用方法<!--加载中用法isLoading:是否加载isEnd:是否结束加载--><cc-paging:isLoad......
  • 前端Vue自定义发送短信验证码弹框popup 实现剩余秒数计数 重发短信验证码
    前端Vue自定义发送短信验证码弹框popup实现剩余秒数计数重发短信验证码,请访问uni-app插件市场地址:https://ext.dcloud.net.cn/plugin?id=13207效果图如下:实现代码如下:cc-codeDialog使用方法<!--show:是否显示弹框phone:手机号 autoCountdown:自动时间秒数len:短信......
  • 前端Vue自定义验证码密码登录切换tabs选项卡标签栏标题栏 验证码登录模版 密码登录模
    前端Vue自定义验证码密码登录切换tabs选项卡标签栏标题栏验证码登录模版密码登录模版,请访问uni-app插件市场地址:https://ext.dcloud.net.cn/plugin?id=13221效果图如下:实现代码如下:cc-selectBox使用方法<!--select-arr:选择数组nowindex:当前选择序列@change:切换选择......
  • Spring Cloud Gateway编码实现任意地址跳转
    欢迎访问我的GitHub这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos本篇概览作为《SpringCloudGateway实战》系列的第十四篇,本文会继续发掘SpringCloudGateway的潜力,通过编码体验操控网关的乐趣,开发出一个实用的功能:让SpringCloudGa......
  • spring cloud nacos的负载均衡
    SpringCloudNacos提供了负载均衡的能力,以在服务调用时实现分布式系统中的负载均衡。下面是SpringCloudNacos负载均衡的详细说明:在SpringCloud中,负载均衡是通过Ribbon这个负载均衡器来实现的。而SpringCloudNacos使用了Ribbon作为默认的负载均......