The main features of Spring Boot exception handling

The main features of Spring Boot exception handling

Exception handling is a very important part of web applications. In Spring Boot, exception handling is very simple and flexible. This article will introduce the main features of Spring Boot exception handling, and provide some sample code to help you better understand.

insert image description here

The main features of exception handling

The exception handling of Spring Boot has the following main features:

1. Unified exception handling

In Spring Boot, you can use @ControllerAdviceand @ExceptionHandlerannotations to achieve unified exception handling. @ControllerAdviceAnnotations are used to define global exception handling classes while @ExceptionHandlerannotations are used to define methods to handle specific exceptions. By using these annotations, the exception handling logic can be separated from the controller, making the code clearer and more maintainable.

For example, the following code demonstrates how to use @ControllerAdviceand @ExceptionHandlerannotations to handle NumberFormatExceptionexceptions :

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(NumberFormatException.class)
    public ResponseEntity<String> handleNumberFormatException(NumberFormatException ex) {
        return ResponseEntity.badRequest().body("Invalid number format");
    }
}

In the above code, we define a global exception handling class GlobalExceptionHandlercalled and use @ExceptionHandlerannotations to handle NumberFormatExceptionexceptions . If NumberFormatExceptionan exception , this method is called to handle the exception and return an HTTP 400 error response.

2. Custom exceptions

In Spring Boot, you can use custom exceptions to represent specific error conditions and associate them with HTTP response status codes. By using these custom exceptions, you can better control the exception handling process and provide more detailed error information.

For example, the following code demonstrates how to define a custom exception UserNotFoundExceptionnamed to indicate a user not found error condition:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(Long id) {
        super("User not found with id: " + id);
    }
}

In the code above, we define a custom exception UserNotFoundExceptionnamed and use @ResponseStatusannotations to associate it with the HTTP 404 response status code. If UserNotFoundExceptionan exception , an HTTP 404 error response will be returned.

3. Priority of exception handlers

In Spring Boot, multiple exception handlers can be used to handle different types of exceptions. When an exception is thrown in the controller, Spring Boot will call the corresponding processing method according to the priority of the exception handler from high to low until it finds a handler that can handle the exception.

For example, the following code demonstrates how to define two exception handlers and set their priorities:

@ControllerAdvice
public class GlobalExceptionHandler1 {
    @ExceptionHandler(Throwable.class)
    public ResponseEntity<String> handleThrowable(Throwable ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal server error");
    }
}

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler2 {
    @ExceptionHandler(Throwable.class)
    public ResponseEntity<String> handleThrowable(Throwable ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Bad request");
    }
}

In the code above, we define two exception handlers and set their priority using @Orderannotations . If an exception is thrown in the controller, Spring Boot will call handleThrowablethe methods and return the corresponding HTTP response.

Summarize

In this article, we introduced the main features of Spring Boot exception handling and provided some sample code to help you understand better. The exception handling of Spring Boot has the characteristics of simplicity, flexibility, unity and customization, which can greatly simplify the exception handling process and provide more detailed error information. Hope this article is helpful to you, thanks for reading!

Here is the complete sample code:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(NumberFormatException.class)
    public ResponseEntity<String> handleNumberFormatException(NumberFormatException ex) {
        return ResponseEntity.badRequest().body("Invalid number format");
    }
}

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(Long id) {
        super("User not found with id: " + id);
    }
}

@ControllerAdvice
public class GlobalExceptionHandler1 {
    @ExceptionHandler(Throwable.class)
    public ResponseEntity<String> handleThrowable(Throwable ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal server error");
    }
}

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler2 {
    @ExceptionHandler(Throwable.class)
    public ResponseEntity<String> handleThrowable(Throwable ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Bad request");
    }
}

Guess you like

Origin blog.csdn.net/it_xushixiong/article/details/131341842