背景
当下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
本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。