Spring-boot Combat "07" "Turn": Unified exception handling for Web applications in Spring boot

Source: Internet
Author: User

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

Choose a previously implemented web App (Chapter3-1-2) to start the app, access a nonexistent URL, or modify the processing to throw an exception directly, such as:

1234 @RequestMapping ("/hello") Public String Hello() throws Exception {throw new Exception ("error occurred") ;}

At this point, you can see an error page similar to the following, which is the default error mapping page provided by spring BOOT.

alt= default error page

Unified exception Handling

Although the default error mapping is implemented in Spring boot, in practice, your error page is not friendly to the user, and we usually need to implement our own exception hints.

Here we use the previous Web application example as the foundation (CHAPTER3-1-2), the transformation of unified exception processing.

    • Create a global exception-handling class by using the @ControllerAdvice definition of a uniform exception-handling class, rather than being defined individually in each controller. To @ExceptionHandler define the type of exception the function is targeting, and finally map the exception object and the request URL to the error.html
123456789101112131415 @ControllerAdvice class Span class= "title" >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; }  }
    • Implementation error.html page display: Created in the templates directory error.html , the requested URL and the exception object's message output.
123456789101112 <! DOCTYPE html><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>

To launch the app, Access: http://localhost:8080/hello , you can see the following error prompt page.

alt= a custom error page

By implementing the above, we only need to Controller throw in the Exception , of course we may have a variety of different Exception . Then, in the @ControllerAdvice class, Exception match the @ExceptionHandler error mapping and processing according to the exception type that is configured in the specific type match that is thrown.

Return JSON format

In the example above, @ControllerAdvice mapping to different error handling pages by unifying the different exception is defined. And when we want to implement the RESTful API, the error returned is JSON-formatted data, not HTML pages, which we can easily support.

Essentially, @ExceptionHandler @ResponseBody you can convert the contents of the return of the handler function into JSON format simply by adding it later.

The following is a concrete example to implement exception handling that returns JSON format.

    • Create a unified JSON return object, code: Message type, message: Content, URL: Requested url,data: Request returned data
12345678910111213 public class errorinfo<t> { public static final Integer OK = 0 ; public static final Integer ERROR = + ; private Integer code; private String message; private String URL; private T data; //Omit getter and setter }
    • Create a custom exception to experiment with catching the exception and return the JSON
1234567 public class myexception extends Exception { public myexception (String message) {  super (message);} }
    • ControllerAdd JSON mappings, throw MyException exceptions
123456789 @Controller public class Hellocontroller { @RequestMapping ("/json")public String JSON() throws myexception {throw new MyException ("Error 2 occurred" );} }
    • MyExceptioncreate a corresponding processing for an exception
123456789101112131415 @Controlle Radvice public class Globalexceptionhandler {   @ExceptionHandler (value = Myexception.class) @ResponseBody Public errorinfo<string> jsonerrorhandlerthrows Exception { errorinfo<string> R = new errorinfo<> (); R.setmessage (E.getmessage ()); R.setcode (Errorinfo.error); R.setdata ( R.seturl (Req.getrequesturl (). toString ()); return r; }  }
    • Launch app, Access: Http://localhost:8080/json, you can get the following return content:
123456 {code: + ,data: " Some data",message: "Error 2 occurred",URL: "http://localhost:8080/ JSON "}

Now that you have finished creating uniform exception handling in spring boot, the actual implementation is still dependent on spring MVC annotations, and more in-depth use can refer to the documentation for spring MVC.

Complete example of this article: chapter3-1-6

Spring-boot Combat "07" "Turn": Unified exception handling for Web applications in Spring boot

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.