search
HomeJavajavaTutorialAnalysis of the principles of SpringBoot exception handling

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;
	}

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();
    }
}

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool