zoukankan      html  css  js  c++  java
  • SpringBoot/SpringMVC Restful接口全局异常处理

    背景

    当下restful接口编程风格流行,大家争相晋仿,笔者最近的开发框架自定义了校验客户端传过来JSON的工具类。

    在接收到客户端json参数时可以校验是否存在非法sql注入参数。

    由于接口返回400,前端没处理,直接导致前端无响应。

    现在要对其进行改造,让前端可以正常接获得异常信息。

    解决方法

    新建一个controller异常处理增强类

    import org.springframework.core.Ordered;
    import org.springframework.core.annotation.Order;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.http.converter.HttpMessageNotReadableException;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.context.request.WebRequest;
    import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
    
    import static com.h2.mes.common.RestfulResponseMessage.SYSTEM_ERROR;
    
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ControllerAdvice
    public class RestExceptionHandler extends ResponseEntityExceptionHandler {
    
        @Override
        protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
            final String errorMessage = ex.getMessage();
            final String[] msgs = errorMessage.split(";");
            return ResponseEntity.ok(RestfulResponseMessage.errorResult(SYSTEM_ERROR,msgs[0]));
        }
    }

    其中

    RestfulResponseMessage.errorResult(SYSTEM_ERROR,msgs[0])
    是封装的自定义异常信息方法
    改善后效果

    参考资料:https://www.toptal.com/java/spring-boot-rest-api-error-handling

     https://www.springboottutorial.com/spring-boot-exception-handling-for-rest-services

    本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
    创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
  • 相关阅读:
    18天,也能让ERP步入新世界
    VB.NET显示Internet上的图片
    首页增强外挂 vBulltein 3.5.x/3.6.x
    简繁互相切换的字库(比较全)
    delphi 使用者的一个好工具
    sql语句的一些参考
    错误2203,安装中的用户权限问题
    音响的灵魂! 世界顶级扬声器品牌介绍
    Pocket PC程序安装
    清理数据库挂马代码
  • 原文地址:https://www.cnblogs.com/passedbylove/p/14345396.html
Copyright © 2011-2022 走看看