The problem

When our project goes online, when the user accesses a URL and executes a controller method, there will be a sudden exception, and then the page will show an error message, which will lead to poor user experience and make others doubt our strength.

Such as:

@Controller
public class UserControllerr {
    @ResponseBody
    @RequestMapping("/java")
    public String Test(a) {
        int a = 1 / 0; // This code will throw a division by 0 exception
        return "asd"; }}Copy the code

When users perform http://localhost:8080/java error screenshot:

It’s a simple mistake, and sometimes it’s even scarier

Think about:

So when an exception occurs, can we handle the exception uniformly, specify the JSON format to return or redirect to an error page?

Operation steps:

1. Import coordinates

2. Create an exception handling class with the @controllerAdvice annotation at the top

3. Create a method in the exception class you define, and some operation logic when an exception occurs

Add @ExceptionHandler() to the method you created.

5. In @ExceptionHandler(), write the type of exception you want to handle.

6. @ExceptionHandler(exception.class), which indicates that this method is executed when all exceptions occur, so this is the local Exception handling method

@controlleradvice, a new annotation available in Spring3.2, is a Controller enhancer that adds logic to Controller methods annotated by @requestmapping. The most common is exception handling

The operation code is as follows:

Import the coordinates

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
Copy the code

Code implementation:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String excetionHandlerTest(a){
        return "The system is being maintained!";
    }
Copy the code

Conclusion:

1. @ExceptionHandler(exception.class), exception. class: This method is executed for all exceptions.

2, If you want to use specific exception logic, you can customize the exception and write the exception you want to handle in the @ExceptionHandler parentheses.

If you run into problems with this code please add to it 960513! Help you quickly master this function code!