Home > Java > javaTutorial > Analysis of the principles of SpringBoot exception handling

Analysis of the principles of SpringBoot exception handling

WBOY
Release: 2023-05-13 23:28:13
forward
1283 people have browsed it

Exception handling process

Execute the target method. Any exception during the running of the target method will be caught by catch and mark the end of the current request. dispatchException throws an exception

Analysis of the principles of SpringBoot exception handling

Enter the view parsing process and render the page. When an exception occurs, the parameter mv is empty and the captured exception dispatchException## is passed in.

Analysis of the principles of SpringBoot exception handling

#Handle the exception that occurs in

handler, and return ModelAndView

Analysis of the principles of SpringBoot exception handling

(1) Traverse all

HandlerExceptionResolvers and find the parser that can handle the current exception to resolve the exception

Analysis of the principles of SpringBoot exception handling

(2) Call

resolveExceptionResolve the exception, pass in the request and response objects, which method, the exception occurred, and then customize the exception handling to return ModelAndView

Analysis of the principles of SpringBoot exception handling

(3) System default exception parser

Analysis of the principles of SpringBoot exception handling

DefaultErrorAttributesFirst handle the exception and The information is saved to the request field and returned null

Analysis of the principles of SpringBoot exception handling##②

ExceptionHandlerExceptionResolver

is used to process annotations@ExceptionHandlerAnnotated method exception

ResponseStatusExceptionResolver

Used to handle method exceptions annotated with @ResponseStatus

DefaultHandlerExceptionResolver

Default processor exception parser, handles some common exceptions (4) If no parser can handle the exception, the exception will be thrown

Analysis of the principles of SpringBoot exception handling(5) If no parser can handle the current exception, a

/error

request will eventually be sent to forward the saved exception information to /error. BasicErrorController is specially used to handle /error requests. BasicErrorController will traverse all ErrorViewResolver to parse error views. If there is no custom error view parsing The default DefaultErrorViewResolver will be used, and the response code will be used as the address of the error page. The template engine will eventually respond to this page. Several exception handling methods and principles

1. Customize the error page,

error/404.html

, error/5xx.html. If there is an accurate error status code page, it will be matched accurately. If there is no page, look for 4xx.html. If there is no page, it will trigger a white page. 2. Use

@ControllerAdvice

and @ExceptionHandler handles global exceptions, the bottom layer is supported by ExceptionHandlerExceptionResolver

##3. Use Analysis of the principles of SpringBoot exception handling@ResponseStatus

and self Define exceptions. The bottom layer is

ResponseStatusExceptionResolver. The bottom layer calls response.sendError(statusCode, resolvedReason), and Tomcat will receive an error. At the end of the request, an empty ModelAndView is returned, so that no processing parser can handle the current exception, and the /error request will eventually be sent, BasicErrorController is specially used to handle /error requests and adapt to 4xx.html or 5xx.html pages

4. Spring underlying exceptions, such as parameter type conversion exceptions. The bottom layer is

DefaultHandlerExceptionResolverAnalysis of the principles of SpringBoot exception handling that handles exceptions at the bottom of the framework. The bottom layer is also
response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE)

. Tomcat will receive an

error. At the end of the request, an empty ModelAndView is returned, so that no processing parser can handle the current exception, and the /error request will eventually be sent, BasicErrorController is specially used to handle /error requests, adapting to 4xx.html or 5xx.html page

protected ModelAndView doResolveException(
			HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {

		try {
			if (ex instanceof HttpRequestMethodNotSupportedException) {
				return handleHttpRequestMethodNotSupported(
						(HttpRequestMethodNotSupportedException) ex, request, response, handler);
			}
			else if (ex instanceof HttpMediaTypeNotSupportedException) {
				return handleHttpMediaTypeNotSupported(
						(HttpMediaTypeNotSupportedException) ex, request, response, handler);
			}
			else if (ex instanceof HttpMediaTypeNotAcceptableException) {
				return handleHttpMediaTypeNotAcceptable(
						(HttpMediaTypeNotAcceptableException) ex, request, response, handler);
			}
			else if (ex instanceof MissingPathVariableException) {
				return handleMissingPathVariable(
						(MissingPathVariableException) ex, request, response, handler);
			}
			else if (ex instanceof MissingServletRequestParameterException) {
				return handleMissingServletRequestParameter(
						(MissingServletRequestParameterException) ex, request, response, handler);
			}
			else if (ex instanceof ServletRequestBindingException) {
				return handleServletRequestBindingException(
						(ServletRequestBindingException) ex, request, response, handler);
			}
			else if (ex instanceof ConversionNotSupportedException) {
				return handleConversionNotSupported(
						(ConversionNotSupportedException) ex, request, response, handler);
			}
			else if (ex instanceof TypeMismatchException) {
				return handleTypeMismatch(
						(TypeMismatchException) ex, request, response, handler);
			}
			else if (ex instanceof HttpMessageNotReadableException) {
				return handleHttpMessageNotReadable(
						(HttpMessageNotReadableException) ex, request, response, handler);
			}
			else if (ex instanceof HttpMessageNotWritableException) {
				return handleHttpMessageNotWritable(
						(HttpMessageNotWritableException) ex, request, response, handler);
			}
			else if (ex instanceof MethodArgumentNotValidException) {
				return handleMethodArgumentNotValidException(
						(MethodArgumentNotValidException) ex, request, response, handler);
			}
			else if (ex instanceof MissingServletRequestPartException) {
				return handleMissingServletRequestPartException(
						(MissingServletRequestPartException) ex, request, response, handler);
			}
			else if (ex instanceof BindException) {
				return handleBindException((BindException) ex, request, response, handler);
			}
			else if (ex instanceof NoHandlerFoundException) {
				return handleNoHandlerFoundException(
						(NoHandlerFoundException) ex, request, response, handler);
			}
			else if (ex instanceof AsyncRequestTimeoutException) {
				return handleAsyncRequestTimeoutException(
						(AsyncRequestTimeoutException) ex, request, response, handler);
			}
		}
		catch (Exception handlerEx) {
			if (logger.isWarnEnabled()) {
				logger.warn("Failure while trying to resolve exception [" + ex.getClass().getName() + "]", handlerEx);
			}
		}
		return null;
	}
Copy after login

5. Custom implementation HandlerExceptionResolver handles exceptions and can be used as the default global exception handling rule

@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Component
public class CustomerHandlerExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        try {
            response.sendError(521,"I love you !");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ModelAndView();
    }
}
Copy after login

Analysis of the principles of SpringBoot exception handling

ErrorViewResolver Implement custom exception handling.

(1) When the bottom layer calls response.sendError, the error request will be forwarded to basicErrorController by default, BasicErrorController Specially used to handle /error requests, adapting 4xx.html or 5xx.html pages

(2) If there is no parser for the exception It can be handled, and the bottom layer of tomcat will also call response.sendError. errorThe request will be forwarded to basicErrorController by default, BasicErrorController is specially used to handle /error requests, adapting 4xx.html or 5xx.html page.

(3)basicErrorController The page address you want to go to is determined by the ErrorViewResolver error view resolver, that is, adaptation 4xx.html Or 5xx.html page.

The above is the detailed content of Analysis of the principles of SpringBoot exception handling. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template