Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of exception handling in SpringBoot

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "exception handling case analysis in SpringBoot". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this article "exception handling case analysis in SpringBoot" can help you solve the problem.

I. background

In the process of writing a program, all kinds of exceptions may occur at any time in the program, so how do we handle all kinds of exceptions gracefully?

II. Demand

1. Intercept some exceptions in the system and return a custom response.

For example:

A HttpRequestMethodNotSupportedException exception occurred on the system. We need to return the following information.

Status code of http: returns 405

{code: custom exception code, message: error message}

2. Implement the interception of custom exceptions

Intercept the BizException written by ourselves.

Third, write some basic exception code

1. Introduce jar package

Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-validation

Note:

Spring-boot-starter-validation is introduced to validate the parameters in the request, and then throws an exception when the parameters are not satisfied.

2. Define a custom exception

Public class BizException extends RuntimeException {public BizException () {} public BizException (String message) {super (message);} public BizException (String message, Throwable cause) {super (message, cause);} public BizException (Throwable cause) {super (cause);} public BizException (String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super (message, cause, enableSuppression, writableStackTrace);}}

explain

Provide a / exception/password api, which requires passing a password parameter

1. A MethodArgumentNotValidException exception will be thrown when the password parameter is not passed.

2. When password passes the exception parameter, a BizException exception is thrown.

4. Test

1. What is the response without passing the password parameter

1. Use the default DefaultHandlerExceptionResolver processing

This class DefaultHandlerExceptionResolver is automatically configured by default.

You can see from the above figure that there is a return value of a default field

2. Use ResponseEntityExceptionHandler to process

1. Write exception handling code-use default logic

@ RestControllerAdvicepublic class RestExceptionHandler extends ResponseEntityExceptionHandler {@ Override protected ResponseEntity handleMethodArgumentNotValid (MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {/ / Custom return value return super.handleMethodArgumentNotValid (ex, headers, status, request) here;}}

You can see that the handleMethodArgumentNotValid method calls the method of the parent class directly, even if it is handled by default.

From the above picture, you can see that the return value is empty.

2. Write exception handling code-return value to return custom content

@ Component@RestControllerAdvicepublic class RestExceptionHandler extends ResponseEntityExceptionHandler {@ Override protected ResponseEntity handleMethodArgumentNotValid (MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {/ / Custom return values return super.handleMethodArgumentNotValid (ex, headers, status, request);} @ Override protected ResponseEntity handleHttpRequestMethodNotSupported (HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {Set supportedMethods = ex.getSupportedHttpMethods () / / Custom request return value Map body = new HashMap (4); body.put ("code", "error code"); body.put ("message", "current request method is not supported, supported request method is:" + supportedMethods); return new ResponseEntity (body, headers, status);}}

From the above code, you can see that the handleHttpRequestMethodNotSupported method returns a custom body.

As you can see from the figure above, the return value that we defined is returned.

2. Pass the password parameter to exception1 and use ResponseEntityExceptionHandler or DefaultHandlerExceptionResolver processing

From the above figure, we can see that the returned result is incorrect. We need to customize the returned result.

2. Return a custom exception

1. Write BizException processing code

@ RestControllerAdvicepublic class BizExceptionHandler {@ ExceptionHandler (BizException.class) public ResponseEntity handleBizException (BizException exception) {/ / Custom request return value Map body = new HashMap (4); body.put ("code", "error code"); body.put ("message", "exception message is:" + exception.getMessage ()); return new ResponseEntity (body, HttpStatus.INTERNAL_SERVER_ERROR);}}

2. The test returns the result

From the picture above, we can see that custom information has been returned.

IV. matters needing attention

1. If you implement @ RestControllerAdvice on the custom exception handling class, use @ ExceptionHandler on the annotation method to handle specific exceptions

2. ResponseEntityExceptionHandler handles those exceptions by default

3. Why is the return body empty after an exception occurs after using ResponseEntityExceptionHandler

By default, after the class ResponseEntityExceptionHandler is implemented, the response result of all exceptions handled by this class is null, and we need to handle it ourselves if we want to return other values.

This is the end of the introduction to "exception handling instance Analysis in SpringBoot". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report