When we do Web applications, it is very common for errors to occur during request processing. Spring Boot provides a default mapping: /error. When an exception is thrown in a processing, it is referred to the request for processing, and the request has a global error page to display the exception content.

Select a previously implemented Web application (Chapter3-1-2) as the basis, start the application, access a URL that does not exist, or modify the processing content, directly throw an exception, such as:

@RequestMapping(“/hello”)

Public String hello() throws Exception{throw new Exception(" error "); }Copy the code

At this point, you will see an error page similar to the following, which is the default error mapping page provided by Spring Boot.

Unified exception handling

Although Spring Boot implements the default error mapping, in practice your error page above is not user-friendly, and we often need to implement our own exception notification.

Let’s build on the previous Web application example (Chapter3-1-2) and adapt it to unified exception handling.

  • Create a global exception handling class: by using@ControllerAdviceDefine a uniform exception handling class, rather than one for each Controller.@ExceptionHandlerDefines the type of Exception the function is targeting, and finally maps the Exception object to the request URLerror.htmlIn the
@ControllerAdvice class GlobalExceptionHandler { public static final String DEFAULT_ERROR_VIEW = "error"; @ExceptionHandler( value = Exception.class ) public ModelAndView defaultErrorHandler( HttpServletRequest req, Exception e ) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject( "exception", e ); mav.addObject( "url", req.getRequestURL() ); mav.setViewName( DEFAULT_ERROR_VIEW ); return(mav); }}Copy the code
  • implementationerror.htmlPage display: intemplatesDirectory creationerror.html, output the requested URL and message of the Exception object.
< HTML > <head lang="en"> <meta Charset ="UTF-8"> <title> Unified exception handling </title> </head> <body> <h1> Error Handler </h1> <div th:text="${url}"></div> <div th:text="${exception.message}"></div> </body> </html>Copy the code

Start the application, visit: http://localhost:8080/hello, you can see the following error page.

After implementing the above, we only need to throw exceptions in the Controller, although we may have many different exceptions. Then in the @ControllerAdvice class, the error mapping and handling are matched based on the specific Exception type thrown matching the Exception type configured in @ExceptionHandler.

2. Return the JSON format

In the example above, we use @ControllerAdvice to uniformly define different exceptions to map to different error handling pages. It’s easy to support RESTful apis that return errors in JSON format instead of HTML pages.

Essentially, simply adding @responseBody after @ExceptionHandler converts the content of the handler function return to JSON format.

Here is a concrete example of exception handling that returns JSON.

  • Create uniform JSON return objects: code: message type, message: message content, URL: request URL, data: data returned by request
public class ErrorInfo<T> { public static final Integer OK = 0; public static final Integer ERROR = 100; private Integer code; private String message; private String url; private T data; /* omit getter and setter */}Copy the code
  • Create a custom exception to experiment with catching the exception and return JSON
public class MyException extends Exception { public MyException( String message ) { super(message); }}Copy the code
  • ControllerTo add a JSON mapping, throwMyExceptionabnormal
@Controller

public class HelloController  {
	@RequestMapping( "/json" )

	public String json()  throws MyException
	{
		throw  new  MyException( "发生错误2" );
	}
}
Copy the code
  • forMyExceptionHandle exception creation
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler( value = MyException.class ) @ResponseBody public ErrorInfo<String> jsonErrorHandler( HttpServletRequest req, MyException e ) throws Exception { ErrorInfo<String> r = new ErrorInfo<>(); r.setMessage( e.getMessage() ); r.setCode( ErrorInfo.ERROR ); r.setData( "Some Data" ); r.setUrl( req.getRequestURL().toString() ); return(r); }}Copy the code
  • Start the application, visit: http://localhost:8080/json, you can get the following return content:
{code: 100 data: Some "data" message: "error 2" url: "http://localhost:8080/json"}Copy the code

Third, summary

At this point, we have completed the creation of unified exception handling in Spring Boot. The actual implementation still relies on Spring MVC annotations, and more in-depth use can refer to the Spring MVC documentation. If you find this article helpful, please do not hesitate to give me a thumbs-up. Your support is the biggest encouragement for me. For more Java basics and interview answers, go to GitHub: github.com/Java-Sober/…