我正在使用 Spring boot 来托管 REST API。即使浏览器正在访问 URL 以及自定义数据结构,我也希望始终发送 JSON 响应,而不是使用标准错误响应。
我可以使用 @ControllerAdvice 和 @ExceptionHandler 来处理自定义异常。但我找不到任何好的方法来处理 404 和 401 等标准错误和已处理错误。
有什么好的模式可以做到这一点吗?
对于那些不想使用 Spring Boot 2 的用户@EnableWebMvc
应用程序属性
server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
控制器建议
@RestControllerAdvice
public class ExceptionResolver {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public HashMap<String, String> handleNoHandlerFound(NoHandlerFoundException e, WebRequest request) {
HashMap<String, String> response = new HashMap<>();
response.put("status", "fail");
response.put("message", e.getLocalizedMessage());
return response;
}
}
Source https://skryvets.com/blog/2018/12/27/enhance-exception-handling-when-building-restful-api-with-spring-boot
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)