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

    本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
    创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
  • 相关阅读:
    bfs入门 (HDU
    Codeforces Round #570 (Div. 3)B
    nyoj 277-车牌号 (map, pair, iterator)
    nyoj 276-比较字母大小 (顺序比较, 逆序输出)
    nyoj 275-队花的烦恼一 (stack, push, pop)
    nyoj 274-正三角形的外接圆面积 (R = PI * a * a / 3)
    nyoj 273-字母小游戏 (getline(cin, string))
    nyoj 268-荷兰国旗问题 (count)
    nyoj 266-字符串逆序输出 (isdigit(), geline(cin, my_string))
    nyoj 264-国王的魔镜 (string[-1:-int(str_len/2+1):-1])
  • 原文地址:https://www.cnblogs.com/passedbylove/p/14345396.html
Copyright © 2011-2022 走看看