Introduce wild Map BOSS
Today we’ll look at how SpringBoot handles global exceptions uniformly. Normally, the two main annotations in SpringBoot that are used for global exception handling are @ControllerAdvice and @ExceptionHandler, but today we’re going to do it a different way, Take down our Exception BOSS faster and more beautiful!
Prepare to deploy weapons
The first step is to plan the weapon model
Configuration parameters
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <! --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <! Alibaba </groupId> <artifactId> FastJson </artifactId> The < version > 1.2.47 < / version > < / dependency >Copy the code
Step 2: Upgrade your weapon’s physical damage
The message code class
Public enum ResultCode {SUCCESS("200"),// Successful FAIL("400"),// failed NOT_FOUND("404"),// The interface does not exist INTERNAL_SERVER_ERROR("500"),// ERROR("9999"); private final String code; ResultCode(String code) { this.code = code; } public String code() { return code; }}Copy the code
Step 3: Upgrade your weapon’s spell damage
The message class returned
@Data public class Result<T> { private String code; private String msg; private T data; public Result setCode(ResultCode resultCode) { this.code = resultCode.code(); return this; } public Result setMsg(String msg) { this.msg = msg; return this; } public Result setData(T data) { this.data = data; return this; }}Copy the code
Step 4: Upgrade your weapon level
Back to utility class
Public class ResultGenerator {private static final String DEFAULT_SUCCESS_MESSAGE = "Success "; public static Result getSuccessResult() { return new Result() .setCode(ResultCode.SUCCESS) .setMsg(DEFAULT_SUCCESS_MESSAGE); } public static <T> Result<T> getSuccessResult(T data) { return new Result() .setCode(ResultCode.SUCCESS) .setMsg(DEFAULT_SUCCESS_MESSAGE) .setData(data); } public static Result getFailResult(String msg) { return new Result() .setCode(ResultCode.FAIL) .setMsg(msg); } public static Result getErrorResult(String msg) { return new Result() .setCode(ResultCode.ERROR) .setMsg(msg); }}Copy the code
Step 5: Customize the weapon appearance according to your preferences
Custom exception
public class ServiceException extends RuntimeException { public ServiceException() { } public ServiceException(String message) { super(message); } public ServiceException(String message, Throwable cause) { super(message, cause); }}Copy the code
Synthesis of weapons
Use WebMvcConfigurer to intercept exceptions
Public class WebMvcConfigurer extends WebMvcConfigurationSupport {/ / unified exception handling @ Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { exceptionResolvers.add(new HandlerExceptionResolver() { public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) { Result result = new Result(); Result.setcode (resultcode.fail).setmsg (LLDB etMessage()); if (e instanceof ServiceException) {// A service fails, such as resultcode.fail. log.info(e.getMessage()); } else if (e instanceof NoHandlerFoundException) {result.setcode (resultcode.not_found).setmsg (" interface [" + Request. GetRequestURI () + "] does not exist "); } else if (e instanceof ServletException) { result.setCode(ResultCode.FAIL).setMsg(e.getMessage()); } else {result.setcode (resultcode.internal_server_error).setmsg (" interface [" + request.getrequesturi () + "] internal error, please contact administrator "); String message; if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Format (" error [%s] : %s.%s, error: %s. %s", request.getRequestURI(), handlerMethod.getBean().getClass().getName(), handlerMethod.getMethod().getName(), e.getMessage()); } else { message = e.getMessage(); } log.error(message, e); } responseResult(response, result); return new ModelAndView(); }}); } private void responseResult(HttpServletResponse response, Result result) { response.setCharacterEncoding("UTF-8"); response.setHeader("Content-type", "application/json; charset=UTF-8"); response.setStatus(200); try { response.getWriter().write(JSON.toJSONString(result)); } catch (IOException ex) { log.error(ex.getMessage()); }}}Copy the code
Began to fight
@RestController public class TestController { @GetMapping("getString") public Result getString(String name){ If (stringutils.isEmpty (name)){throw new ServiceException(" empty "); }else if ("boss".equals(name)) {throw new ServiceException(" null "); } int I = 0; i = 5/i; Return ResultGenerator. GetFailResult (" failure "); }}Copy the code
Successful strike
Finally, look at the effect, is it very simple: