In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the global exception handling of SpringBoot". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the global exception handling of SpringBoot".
SpringBoot global exception handling
In order to enable the client to have a better experience, the server should explicitly tell the client the error message when it sends a request to the server.
The interface returned by SpringBoot's built-in exception handling is too messy and unfriendly. We need to encapsulate the exception information to the front end. The purpose of this article is to uniformly encapsulate the error message into the following format json response to the front end.
{code:10001, message:xxxxx, request:GET url}
Custom exception class
Package com.lin.missyou.exception;public class HttpException extends RuntimeException {protected Integer code; protected Integer httpStatusCode; public Integer getCode () {return code;} public void setCode (Integer code) {this.code = code;} public Integer getHttpStatusCode () {return httpStatusCode;} public void setHttpStatusCode (Integer httpStatusCode) {this.httpStatusCode = httpStatusCode;}} package com.lin.missyou.exception Public class NotFoundException extends HttpException {public NotFoundException (int code) {this.httpStatusCode = 404; this.code = code;}} package com.lin.missyou.exception;public class ForbiddenException extends HttpException {public ForbiddenException (int code) {this.httpStatusCode = 403; this.code = code;}}
Create a class UnifyResponse that encapsulates exception information
Package com.lin.missyou.core;public class UnifyResponse {private int code; private String message; private String request; public int getCode () {return code;} public String getMessage () {return message;} public String getRequest () {return request;} public UnifyResponse (int code, String message, String request) {this.code = code; this.message = message This.request = request;}}
Write the exception information in the configuration file exception-code.properties
Lin.codes [10000] = generic exception lin.codes [10001] = generic parameter error
Custom configuration class management profile
Package com.lin.missyou.core.configuration;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component;import java.util.HashMap;import java.util.Map;@PropertySource (value= "classpath:config/exception-code.properties") @ ConfigurationProperties (prefix = "lin") @ Componentpublic class ExceptionCodeConfiguration {private Map codes = new HashMap (); public Map getCodes () {return codes } public void setCodes (Map codes) {this.codes = codes;} public String getMessage (int code) {String message = codes.get (code); return message;}}
Create a global exception handling class GlobalExceptionAdvice, indicating the exception handling class with @ ControllerAdvice. @ ResponseStatus is used to specify the http status code.
@ ExceptionHandler indicates the exception handler and passes in parameters to specify what type of exception the current function will handle. Springboot will help us pass these exception information into the function. The first function is used to handle unknown exceptions and does not need to provide the front end with a detailed cause of the error, but simply prompts for unified text information.
The second function is used to handle known exceptions. You need to specify the cause of the error and customize the httpStatusCode flexibly according to the information passed by the Exception. ResponseEntity can customize many properties, including the ability to set httpheaders,httpbodys,httpStatus.
Package com.lin.missyou.core;import com.lin.missyou.core.config.ExceptionCodeConfiguration;import com.lin.missyou.exception.HttpException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.validation.ObjectError;import org.springframework.web.bind.MethodArgumentNotValidException;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler Import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.ResponseStatus;import javax.servlet.http.HttpServletRequest;import javax.validation.ConstraintViolation;import javax.validation.ConstraintViolationException;import java.util.List;@ControllerAdvicepublic class GlobalExceptionAdvice {@ Autowired ExceptionCodeConfiguration exceptionCodeConfiguration; @ ExceptionHandler (Exception.class) @ ResponseBody @ ResponseStatus (HttpStatus.INTERNAL_SERVER_ERROR) public UnifyResponse handleException (HttpServletRequest req,Exception e) {String method = req.getMethod () String requestUrl = req.getRequestURI (); System.out.println (e); UnifyResponse unifyResponse = new UnifyResponse (9999, "server error", method+ "" + requestUrl); return unifyResponse;} @ ExceptionHandler (HttpException.class) public ResponseEntity handleHttpException (HttpServletRequest req, HttpException e) {String method = req.getMethod (); String requestUrl = req.getRequestURI (); System.out.println (e) UnifyResponse unifyResponse = new UnifyResponse (e.getCode (), exceptionCodeConfiguration.getMessage (e.getCode ()), method+ "" + requestUrl); HttpHeaders httpHeaders = new HttpHeaders (); httpHeaders.setContentType (MediaType.APPLICATION_JSON); HttpStatus httpStatus = HttpStatus.resolve (e.getHttpStatusCode ()); ResponseEntity responseEntity = new ResponseEntity (unifyResponse,httpHeaders,httpStatus); return responseEntity } / / Parameter check @ ExceptionHandler (MethodArgumentNotValidException.class) @ ResponseBody @ ResponseStatus (HttpStatus.BAD_REQUEST) public UnifyResponse handleBeanValidation (HttpServletRequest req, MethodArgumentNotValidException e) {String method = req.getMethod (); String requestUrl = req.getRequestURI (); List errors = e.getBindingResult (). GetAllErrors (); String message = formatAllErrorMessages (errors); return new UnifyResponse (10001) } private String formatAllErrorMessages (List errors) {StringBuffer errorMsg = new StringBuffer (); errors.forEach (error-> errorMsg.append (error.getDefaultMessage ()) .append (";")); return errorMsg.toString ();} @ ExceptionHandler (ConstraintViolationException.class) @ ResponseBody @ ResponseStatus (HttpStatus.BAD_REQUEST) public UnifyResponse handleConstrainException (HttpServletRequest req, ConstraintViolationException e) {String method = req.getMethod () String requestUrl = req.getRequestURI (); String message = e.getMessage (); return new UnifyResponse (10001maxim messagementhod + "" + requestUrl);}}
The response information may be garbled and the configuration file encoding may be modified. Search for File Encodings,Default encoding for properties files in the settings panel. Select UTF-8 and check Transparent native-to-ascii conversion.
Springboot global exception handling-@ ControllerAdvice+ exception handler 1. After the global exception is caught, return json to the browser
Project structure:
1. Custom exception class MyException.java
Package com.gui.restful;/** * Custom exception class * / public class MyException extends RuntimeException {private String code; private String msg; public MyException (String code,String msg) {this.code=code; this.msg=msg;} public String getCode () {return code;} public void setCode (String code) {this.code=code;} public String getMsg () {return msg } public void setMsg (String msg) {this.msg = msg;}}
2. Controller MyController.java
Package com.gui.restful;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;/** * controller throws an exception * / @ RestControllerpublic class MyController {@ RequestMapping ("hello") public String hello () throws Exception {throw new MyException ("system exception");}}
3. Global exception handling class MyControllerAdvice
Package com.gui.restful;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.ResponseBody;import java.util.HashMap;import java.util.Map / * * Global exception capture handling * / @ ControllerAdvice / / controller enhancer public class MyControllerAdvice {@ ResponseBody @ ExceptionHandler (value=MyException.class) / / exception types handled by public Map myExceptionHandler (MyException e) {Map map=new HashMap (); map.put ("code", e.getCode ()); map.put ("msg", e.getMsg ()); return map;}}
4. Running result
Launch the application and access http://localhost:8080/hello. The following result appears, indicating that the custom exception has been intercepted successfully.
Second, after catching the exception globally, return the page to the browser
1. Custom exception class MyException.java (ditto)
2. Controller MyController.java (ditto)
3. Global exception handling class MyControllerAdvice
Package com.gui.restful;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import java.util.HashMap;import java.util.Map / * * Global exception capture handling * / @ ControllerAdvice / / controller enhancer public class MyControllerAdvice {@ ExceptionHandler (value=MyException.class) / / exception type handled by public ModelAndView myExceptionHandler (MyException e) {ModelAndView modelAndView=new ModelAndView (); modelAndView.setViewName ("error"); modelAndView.addObject ("code", e.getCode ()); modelAndView.addObject ("msg", e.getMsg ()); return modelAndView;}}
4. Page rendering error.ftl (rendering with freemarker)
Introducing freemarker dependency into pom.xml
Org.springframework.boot spring-boot-starter-freemarker
Error.ftl
Error page code:$ [code] msg:$ {msg}
5. Running result
Launch the application and access http://localhost:8080/hello. The following result appears, indicating that the custom exception has been intercepted successfully.
Thank you for your reading. the above is the content of "what is the global exception handling of SpringBoot". After the study of this article, I believe you have a deeper understanding of what the global exception handling of SpringBoot is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.