背景

当下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

posted on 2021-01-29 15:54  你不知道的浪漫  阅读(227)  评论(0编辑  收藏  举报