In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly analyzes the relevant knowledge points about how to unify the Restful API return value format and how to deal with exceptions in Spring Boot. The content is detailed and easy to understand, and the operation details are reasonable, so it has a certain reference value. If you are interested, you might as well follow the editor to take a look, and follow the editor to learn more about "unifying the format of Restful API return values and unified handling of exceptions in Spring Boot".
Unified return value
Today, with the popular separation of front and rear ends, having a unified return value format can not only make our interface look more beautiful, but also make the front end handle a lot of things and avoid a lot of problems.
The general format of return values is as follows:
Public class Result {/ / API call success or failure private Integer code = 0; / / specific code private String errorCode of failure = ""; / / Information to be passed, such as error message private String msg; / / data to be passed private T data;.}
The original APIs are as follows:
@ GetMapping ("/ test") public User test () {return new User ();}
When we need a unified return value, we might use this approach:
GetMapping ("/ test") public Result test () {return Result.success (new User ());}
This method does achieve the goal of unifying the return value of the interface, but several new problems have emerged:
The return value of the interface is not obvious, and the return value of the interface cannot be seen at a glance.
Each interface requires an additional amount of code.
Fortunately, Spring Boot has provided us with a better solution by adding the following code to the project to unknowingly unify the global return values for us.
/ * * Global return value uniformly encapsulated * / @ EnableWebMvc @ Configuration public class GlobalReturnConfig {@ RestControllerAdvice static class ResultResponseAdvice implements ResponseBodyAdvice {@ Override public boolean supports (MethodParameter methodParameter, Class > aClass) {return true @ Override public Object beforeBodyWrite (Object body, MethodParameter methodParameter, MediaType mediaType, Class > aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {if (body instanceof Result) {return body;} return new Result (body);}}
And our interface only needs to be written in the most primitive form.
@ GetMapping ("/ test") public User test () {return new User ();}
Unified handling of exceptions
When encapsulating the return value uniformly, we did not consider the situation when the interface throws an exception. It is certainly not friendly for users to see the server exception directly when the API throws an exception, and it is impossible for every interface to go to try/catch to handle it. In this case, you only need to use the @ ExceptionHandler annotation to handle exceptions globally without awareness.
@ RestControllerAdvice public class GlobalExceptionHandler {private static final Logger LOG = LoggerFactory.getLogger (GlobalExceptionHandler.class); / * * Global exception handling * / @ ExceptionHandler public JsonData handleException (HttpServletRequest request, HttpServletResponse response, final Exception e) {LOG.error (e.getMessage (), e) If (e instanceof AlertException) {/ / exception if (AlertException) e). GetRetCode ()! = null) {/ / predefined exception return new Result (AlertException) e). GetRetCode ());} else {return new Result (1, e.getMessage ()! = null? E.getMessage (): ");}} else {/ / other exception if (Util.isProduct ()) {/ / if it is a formal environment, unified prompt return new Result (RetCode.ERROR);} else {/ / test environment, alert exception information return new Result (1, StringUtils.isNotBlank (e.getMessage ())? E.getMessage (): e.toString ();}}
The AlertException is our custom exception, so when an error needs to be thrown in the business, AlertException can be thrown manually.
These are the two steps to uniformly handle the return value and the exception.
On the "unified Restful API return value format in Spring Boot and unified handling of exceptions how to solve" is introduced here, more related content can search the previous article, hope to help you answer questions, please support the website!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.