Spring REST 接口自定义404响应内容

版本说明:Spring Boot 2.0.1.RELEASE

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

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

如果不想返回此内容,需要做如下配置:

application.yml

spring: 
  mvc:
    throw-exception-if-no-handler-found: true
  resources:
    add-mappings: false

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

异常捕获

在项目中我使用了全局异常处理,如下:

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    public ResponseEntity<Object> handleExceptions(Exception ex, WebRequest request) {
        logger.error("Exception", ex);
        mailPublisher.publishMailToAdministrator(ex);

        return handleExceptionInternal(ex, RESPONSE_ERROR, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }
    
    /**
     * Handle NoHandlerFoundException
     * @param ex
     * @param headers
     * @param status
     * @param request
     * @return
     */
    @Override
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return handleExceptionInternal(ex, RESPONSE_ERROR, headers, status, request);
    }    
    
}

重写ResponseEntityExceptionHandler的handleNoHandlerFoundException方法来处理404异常,注意不要在全局异常处理中添加如下方法:

    @ExceptionHandler(value = {NoHandlerFoundException.class})
    public ResponseEntity<Object> handleNotFoundExceptions(NoHandlerFoundException ex) {
        return handleExceptionInternal(ex, RESPONSE_ERROR, new HttpHeaders(), HttpStatus.NOT_FOUND, null);
    }

否则会抛出如下异常,因为ResponseEntityExceptionHandler.handleException已经注册了对该异常的处理,如果我们再注册一个,会有两个异常处理,导致Ambiguous。

Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.servlet.NoHandlerFoundException]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,941评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,315评论 6 342
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 23,036评论 1 92
  • 四月的天气,乍暖还寒,在一家安静的茶馆,我紧挨着眼睛微红的h坐下,好让她感觉到我想要给她的温暖,虽然早已过...
    sx遥望阅读 204评论 0 1
  • 原来年初的时候帮朋友搞一个项目的App程序,安卓的比较方便,苹果的在手机上测试调试了好久才成功,现在把经验分享一下...
    IT小C阅读 991评论 0 1

友情链接更多精彩内容