In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how the spring Boot project handles global exceptions". In the daily operation, I believe that many people have doubts about how to deal with global exceptions in spring Boot projects. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how spring Boot projects deal with global exceptions". Next, please follow the editor to study!
Preface
Exception handling is an insurmountable hurdle in our daily development. How to handle exceptions gracefully in Spring Boot projects is the direction we need to study in this lesson.
Classification of anomalies
In a Spring Boot project, we can divide exceptions into two types, the first is before the request reaches the Controller layer, and the second is the error that occurs in the project code after it reaches the Controller layer. The first can be divided into two types of errors: 1. Path error 2. Similar to request method error, parameter type is not equal to similar error.
Define ReturnVO and ReturnCode
In order to keep the return values uniform, we define a class ReturnVO returned uniformly and an enumeration class ReturnCode that records error return codes and error messages. The specific error information and error codes are saved in response.properties and read using streams.
ReturnVOpublic class ReturnVO {private static Properties properties = ReadPropertiesUtil.getProperties (System.getProperty ("user.dir") + CommonUrl.RESPONSE_PROP_URL); / * * return code * / private String code; / * * return information * / private String message; / * return data * / private Object data; public Object getData () {return data } public void setData (Object data) {this.data = data;} public String getMessage () {return message;} public void setMessage (String message) {this.message = message;} public String getCode () {return code;} public void setCode (String code) {this.code = code } / * default construction, return the correct return code and information * / public ReturnVO () {this.setCode (properties.getProperty (ReturnCode.SUCCESS.val (); this.setMessage (properties.getProperty (ReturnCode.SUCCESS.msg () } / * return code, here you need to define * @ param code * / public ReturnVO (ReturnCode code) {this.setCode (properties.getProperty (code.val (); this.setMessage (properties.getProperty (code.msg () in the enumeration } / * returns data. By default, correct code and message * @ param data * / public ReturnVO (Object data) {this.setCode (properties.getProperty (ReturnCode.SUCCESS.val (); this.setMessage (properties.getProperty (ReturnCode.SUCCESS.msg (); this.setData (data) are returned } / * returns the error code and custom error message * @ param code * @ param message * / public ReturnVO (ReturnCode code, String message) {this.setCode (properties.getProperty (code.val (); this.setMessage (message) } / * returns custom code,message and data * @ param code * @ param message * @ param data * / public ReturnVO (ReturnCode code, String message, Object data) {this.setCode (code.val ()); this.setMessage (message); this.setData (data) } @ Override public String toString () {return "ReturnVO {" + "code='" + code +'\'+ ", message='" + message +'\'+ ", data=" + data +'}';}} ReturnCode
Other error handling only needs to add the corresponding exception to the enumeration class, and the name of the enumeration should be defined as the name of the exception, so that you don't have to modify other code directly, and when you add a new exception, just add the fields in the enumeration class and the properties in the properties file.
Public enum ReturnCode {/ * * Operation succeeded * / SUCCESS ("SUCCESS_CODE", "SUCCESS_MSG"), / * * Operation failed * / FAIL ("FAIL_CODE", "FAIL_MSG"), / * Null pointer exception * / NullPointerException ("NPE_CODE", "NPE_MSG"), / * * the return value of custom exception is * / NullResponseException ("NRE_CODE"). "NRE_MSG"), / * * runtime exception * / RuntimeException ("RTE_CODE", "RTE_MSG"), / * * request method error * / HttpRequestMethodNotSupportedException ("REQUEST_METHOD_UNSUPPORTED_CODE", "REQUEST_METHOD_UNSUPPORTED_MSG"), / * * INTERNAL_ERROR * / BindException ("BIND_EXCEPTION_CODE", "BIND_EXCEPTION_MSG") / * * incorrect page path * / UrlError ("UE_CODE", "UE_MSG") Private ReturnCode (String value, String msg) {this.val = value; this.msg = msg;} public String val () {return val;} public String msg () {return msg;} private String val; private String msg;} response.properties
Here I have customized some exceptions for later testing, and we need to define a lot of exceptions to improve in our actual project.
SUCCESS_CODE=2000SUCCESS_MSG= operation succeeded FAIL_CODE=5000FAIL_MSG= operation failed NPE_CODE=5001NPE_MSG= null pointer exception NRE_CODE=5002NRE_MSG= return value is null RTE_CODE=5001RTE_MSG= runtime exception UE_CODE=404UE_MSG= page path error REQUEST_METHOD_UNSUPPORTED_CODE=4000REQUEST_METHOD_UNSUPPORTED_MSG= request mode exception BIND_EXCEPTION_CODE=4001BIND_EXCEPTION_MSG= request parameter binding failed path error handling
Here, the path error is handled by implementing the ErrorController interface, and then implementing the getErrorPath () method:
/ * author yangwei * @ since 2019-01-02 18:13 * / @ RestControllerpublic class RequestExceptionHandler implements ErrorController {@ Override public String getErrorPath () {return "/ error";} @ RequestMapping ("/ error") public ReturnVO errorPage () {return new ReturnVO (ReturnCode.UrlError);}}
You can test it here:
Use ControllerAdvice to handle other types of exceptions
Similar to the request parameter error, request method error, incorrect data format and so on before arriving at Controller, all of these errors are classified as one type. Here we only show how to handle the request error.
/ * * Global exception handling class * @ author yangwei * * is used to return json globally. If you want to return ModelAndView, use ControllerAdvice * inherit ResponseEntityExceptionHandler and catch some exceptions similar to request method exceptions * / @ RestControllerAdvicepublic class GlobalExceptionHandler extends ResponseEntityExceptionHandler {private static Properties properties = ReadPropertiesUtil.getProperties (System.getProperty ("user.dir") + CommonUrl.RESPONSE_PROP_URL) / * rewrite handleExceptionInternal and customize the handling process * * / @ Override protected ResponseEntity handleExceptionInternal (Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {/ / the exception is passed directly to the handlerException () method for handling. The return value is OK to ensure a friendly return instead of 500error code. Return new ResponseEntity (handlerException (ex), HttpStatus.OK);} / * * exception catch * @ param e caught exception * @ return encapsulated return object * * / @ ExceptionHandler (Exception.class) public ReturnVO handlerException (Throwable e) {ReturnVO returnVO = new ReturnVO (); String errorName = e.getClass (). GetName () ErrorName = errorName.substring (errorName.lastIndexOf (".") + 1); / / if an exception is not defined but a runtime exception is thrown directly, you need to enter the following branch if (e.getClass () = = RuntimeException.class) {returnVO.setMessage (valueOf ("RuntimeException"). Msg ()) + ":" + e.getMessage ()) ReturnVO.setCode (properties.getProperty (valueOf ("RuntimeException"). Val ());} else {returnVO.setMessage (properties.getProperty (valueOf (errorName). Msg ()); returnVO.setCode (properties.getProperty (valueOf (errorName). Val ());} return returnVO;}}
Here we can test:
@ RestController@RequestMapping (value = "/ user") public class UserController {@ Autowired private IUserService userService; @ PostMapping (value = "/ findAll") public Object findAll () {throw new RuntimeException ("ddd");} @ RequestMapping (value = "/ findAll1") public ReturnVO findAll1 (UserDO userDO) {System.out.println (userDO); return new ReturnVO (userService.findAll1 ()) } @ RequestMapping (value = "/ test") public ReturnVO test () {throw new RuntimeException ("Test non-custom runtime exceptions");}}
Access findAll directly in the browser. The default is the get method. Here, we expect to throw an error with an exception in the request method:
Visit findAll1?id=123ss. Since the id attribute in the UserDO we accept is of type Integer, a parameter binding exception is reported here:
In combination with AOP, put into common modules to reduce code duplication
We did a simple operation on global exception handling using AOP in the last lesson. This lesson has been improved and put it into our common module. When you use it, you only need to import the jar package, and then scan the package path in the startup class configuration.
/ * * Unified encapsulation return value and exception handling * * @ author vi * @ since 6:09 on 2018-12-20 AM * / @ Slf4j@Aspect@Order (5) @ Componentpublic class ResponseAop {@ Autowired private GlobalExceptionHandler exceptionHandler; / * pointcut * / @ Pointcut ("execution (public * indi.viyoung.viboot.*.controller..* (..)") Public void httpResponse () {} / * Ring * / @ Around ("httpResponse ()") public ReturnVO handlerController (ProceedingJoinPoint proceedingJoinPoint) {ReturnVO returnVO = new ReturnVO (); try {Object proceed = proceedingJoinPoint.proceed (); if (proceed instanceof ReturnVO) {returnVO = (ReturnVO) proceed } else {returnVO.setData (proceed);}} catch (Throwable throwable) {/ / here directly call the method returnVO = exceptionHandler.handlerException (throwable) that we just wrote in handler;} return returnVO;}}
After these preparations, we only need to do the following steps when handling exceptions in the future:
Introduction of common module jar package
Configure the scan package path on the startup class
If you add an exception, add it to the enumeration class, and then go to properties to edit the return code and return information (Note: the variable name of the enumeration class must be the same as the exception name)
At this point, the study on "how the spring Boot project handles global exceptions" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.