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

What is the function of ErrorWebFluxAutoConfiguration in spring boot

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What is the role of ErrorWebFluxAutoConfiguration in spring boot? I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

ErrorWebFluxAutoConfiguration

SpringMurbootFluxAutoConfiguration.java ErrorFluxAutoConfiguration.java

@ Configuration@ConditionalOnWebApplication (type = ConditionalOnWebApplication.Type.REACTIVE) @ ConditionalOnClass (WebFluxConfigurer.class) @ AutoConfigureBefore (WebFluxAutoConfiguration.class) @ EnableConfigurationProperties ({ServerProperties.class, ResourceProperties.class}) public class ErrorWebFluxAutoConfiguration {private final ServerProperties serverProperties; private final ApplicationContext applicationContext; private final ResourceProperties resourceProperties; private final List viewResolvers; private final ServerCodecConfigurer serverCodecConfigurer Public ErrorWebFluxAutoConfiguration (ServerProperties serverProperties, ResourceProperties resourceProperties, ObjectProvider viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext) {this.serverProperties = serverProperties; this.applicationContext = applicationContext; this.resourceProperties = resourceProperties This.viewResolvers = viewResolversProvider.orderedStream () .cake (Collectors.toList ()); this.serverCodecConfigurer = serverCodecConfigurer } @ Bean @ ConditionalOnMissingBean (value = ErrorWebExceptionHandler.class, search = SearchStrategy.CURRENT) @ Order (- 1) public ErrorWebExceptionHandler errorWebExceptionHandler (ErrorAttributes errorAttributes) {DefaultErrorWebExceptionHandler exceptionHandler = new DefaultErrorWebExceptionHandler (errorAttributes, this.resourceProperties) This.serverProperties.getError (), this.applicationContext) ExceptionHandler.setViewResolvers (this.viewResolvers); exceptionHandler.setMessageWriters (this.serverCodecConfigurer.getWriters ()); exceptionHandler.setMessageReaders (this.serverCodecConfigurer.getReaders ()); return exceptionHandler } @ Bean @ ConditionalOnMissingBean (value = ErrorAttributes.class, search = SearchStrategy.CURRENT) public DefaultErrorAttributes errorAttributes () {return new DefaultErrorAttributes (this.serverProperties.getError (). IsIncludeException ());}}

ErrorWebFluxAutoConfiguration registered DefaultErrorAttributes and ErrorWebExceptionHandler.

ErrorAttributes

SpringMutual bootMouse 2.1.5.RELEASEsulce sources.jarAccording to orgUnix springframeworkUniverse webAccord reactiveLetWork ErrorAttributes.java

Public interface ErrorAttributes {/ * * Return a {@ link Map} of the error attributes. The map can be used as the model of * an error page, or returned as a {@ link ServerResponse} body. * @ param request the source request * @ param includeStackTrace if stack trace elements should be included * @ return a map of error attributes * / Map getErrorAttributes (ServerRequest request, boolean includeStackTrace); / * * Return the underlying cause of the error or {@ code null} if the error cannot be * extracted. * @ param request the source ServerRequest * @ return the {@ link Exception} that caused the error or {@ code null} * / Throwable getError (ServerRequest request); / * * Store the given error information in the current {@ link ServerWebExchange}. * @ param error the {@ link Exception} that caused the error * @ param exchange the source exchange * / void storeErrorInformation (Throwable error, ServerWebExchange exchange);}

The ErrorAttributes interface defines three methods: getErrorAttributes, getError and storeErrorInformation.

DefaultErrorAttributes

SpringMutual bootMouse 2.1.5.RELEASEsulce sources.jarUnix orgUnix springframeworkhand bootbank webAccord reactiveCharger errorGrease DefaultErrorAttributes.java

Public class DefaultErrorAttributes implements ErrorAttributes {private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName () + ".ERROR"; private final boolean includeException; / * * Create a new {@ link DefaultErrorAttributes} instance that does not include the * "exception" attribute. * / public DefaultErrorAttributes () {this (false);} / * * Create a new {@ link DefaultErrorAttributes} instance. * @ param includeException whether to include the "exception" attribute * / public DefaultErrorAttributes (boolean includeException) {this.includeException = includeException;} @ Override public Map getErrorAttributes (ServerRequest request, boolean includeStackTrace) {Map errorAttributes = new LinkedHashMap (); errorAttributes.put ("timestamp", new Date ()) ErrorAttributes.put ("path", request.path ()); Throwable error = getError (request); HttpStatus errorStatus = determineHttpStatus (error); errorAttributes.put ("status", errorStatus.value ()); errorAttributes.put ("error", errorStatus.getReasonPhrase ()); errorAttributes.put ("message", determineMessage (error)) HandleException (errorAttributes, determineException (error), includeStackTrace); return errorAttributes;} private HttpStatus determineHttpStatus (Throwable error) {if (error instanceof ResponseStatusException) {return ((ResponseStatusException) error) .getStatus () } ResponseStatus responseStatus = AnnotatedElementUtils .findMergedAnnotation (error.getClass (), ResponseStatus.class); if (responseStatus! = null) {return responseStatus.code ();} return HttpStatus.INTERNAL_SERVER_ERROR } private String determineMessage (Throwable error) {if (error instanceof WebExchangeBindException) {return error.getMessage ();} if (error instanceof ResponseStatusException) {return ((ResponseStatusException) error) .getReason () } ResponseStatus responseStatus = AnnotatedElementUtils .findMergedAnnotation (error.getClass (), ResponseStatus.class); if (responseStatus! = null) {return responseStatus.reason ();} return error.getMessage () } private Throwable determineException (Throwable error) {if (error instanceof ResponseStatusException) {return (error.getCause ()! = null)? Error.getCause (): error;} return error;} private void addStackTrace (Map errorAttributes, Throwable error) {StringWriter stackTrace = new StringWriter (); error.printStackTrace (new PrintWriter (stackTrace)); stackTrace.flush (); errorAttributes.put ("trace", stackTrace.toString ()) } private void handleException (Map errorAttributes, Throwable error, boolean includeStackTrace) {if (this.includeException) {errorAttributes.put ("exception", error.getClass (). GetName ());} if (includeStackTrace) {addStackTrace (errorAttributes, error) } if (error instanceof BindingResult) {BindingResult result = (BindingResult) error; if (result.hasErrors ()) {errorAttributes.put ("errors", result.getAllErrors ()) } @ Override public Throwable getError (ServerRequest request) {return (Throwable) request.attribute (ERROR_ATTRIBUTE) .orElseThrow (()-> new IllegalStateException ("Missing exception attribute in ServerWebExchange")) @ Override public void storeErrorInformation (Throwable error, ServerWebExchange exchange) {exchange.getAttributes () .putIfAbsent (ERROR_ATTRIBUTE, error);}}

DefaultErrorAttributes implements the ErrorAttributes interface, and its getErrorAttributes method returns information such as timestamp, path, status, error, message, exception (includeException), trace (includeStackTrace), etc. GetError method gets Throwable;storeErrorInformation from ServerRequest's ERROR_ATTRIBUTE and stores Throwable in ServerWebExchange's attributes

WebExceptionHandler

SpringMuir webMel 5.1.7.RELEASEMAE sources.jarAccording to orgUnix springframeworkhand webUniverse WebExceptionHandler.java

Public interface WebExceptionHandler {/ * * Handle the given exception. A completion signal through the return value * indicates error handling is complete while an error signal indicates the * exception is still not handled. * @ param exchange the current exchange * @ param ex the exception to handle * @ return {@ code Mono} to indicate when exception handling is complete * / Mono handle (ServerWebExchange exchange, Throwable ex);}

WebExceptionHandler defines the handle method

ErrorWebExceptionHandler

SpringMutual bootlue 2.1.5.RELEASEsulce sources.jarAccording to orgUnix springframeworkhand bootbank webAccord reactiveCharger ErrorWebExceptionHandler.java

@ FunctionalInterfacepublic interface ErrorWebExceptionHandler extends WebExceptionHandler {}

ErrorWebExceptionHandler inherits the WebExceptionHandler interface and simply identifies it for render errors by the class name.

AbstractErrorWebExceptionHandlerpublic abstract class AbstractErrorWebExceptionHandler implements ErrorWebExceptionHandler, InitializingBean {/ * * Currently duplicated from Spring WebFlux HttpWebHandlerAdapter. * / private static final Set DISCONNECTED_CLIENT_EXCEPTIONS; static {Set exceptions = new HashSet (); exceptions.add ("AbortedException"); exceptions.add ("ClientAbortException"); exceptions.add ("EOFException"); exceptions.add ("EofException"); DISCONNECTED_CLIENT_EXCEPTIONS = Collections.unmodifiableSet (exceptions) } private static final Log logger = HttpLogging .forLogName (AbstractErrorWebExceptionHandler.class); private final ApplicationContext applicationContext; private final ErrorAttributes errorAttributes; private final ResourceProperties resourceProperties; private final TemplateAvailabilityProviders templateAvailabilityProviders; private List > messageWriters = Collections.emptyList (); private List viewResolvers = Collections.emptyList () Public AbstractErrorWebExceptionHandler (ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext) {Assert.notNull (errorAttributes, "ErrorAttributes must not be null"); Assert.notNull (resourceProperties, "ResourceProperties must not be null"); Assert.notNull (applicationContext, "ApplicationContext must not be null"); this.errorAttributes = errorAttributes This.resourceProperties = resourceProperties; this.applicationContext = applicationContext; this.templateAvailabilityProviders = new TemplateAvailabilityProviders (applicationContext);} /. @ Override public void afterPropertiesSet () throws Exception {if (CollectionUtils.isEmpty (this.messageWriters)) {throw new IllegalArgumentException ("Property 'messageWriters' is required");}} / * * Create a {@ link RouterFunction} that can route and handle errors as JSON responses * or HTML views. *

* If the returned {@ link RouterFunction} doesn't route to a {@ code HandlerFunction} * the original exception is propagated in the pipeline and can be processed by other * {@ link org.springframework.web.server.WebExceptionHandler} s. * @ param errorAttributes the {@ code ErrorAttributes} instance to use to extract error * information * @ return a {@ link RouterFunction} that routes and handles errors * / protected abstract RouterFunction getRoutingFunction (ErrorAttributes errorAttributes) @ Override public Mono handle (ServerWebExchange exchange, Throwable throwable) {if (exchange.getResponse (). IsCommitted () | | isDisconnectedClientError (throwable)) {return Mono.error (throwable);} this.errorAttributes.storeErrorInformation (throwable, exchange) ServerRequest request = ServerRequest.create (exchange, this.messageReaders) Return getRoutingFunction (this.errorAttributes) .route (request) .switchIfEmpty (Mono.error (throwable)) .flatMap ((handler)-> handler.handle (request)) .doOnNext ((response)-> logError (request, response) Throwable) .flatMap ((response)-> write (exchange, response)) } / /.}

AbstractErrorWebExceptionHandler declares to implement the ErrorWebExceptionHandler and InitializingBean interfaces; its handle method first stores the throwable in the errorAttributes summary, and then route;afterPropertiesSet through getRoutingFunction mainly to ensure that the messageWriters is not empty; it defines the getRoutingFunction subclass to implement

DefaultErrorWebExceptionHandler

SpringMyRIBOTHERROR 2.1.5.RELEASERTS sources.jarAccording orgSpringframeworkUniverse bootUniverse autofinancing repositories Web reactiveUniverse errorCandler.java

Public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {private static final Map SERIES_VIEWS; static {Map views = new EnumMap (HttpStatus.Series.class); views.put (HttpStatus.Series.CLIENT_ERROR, "4xx"); views.put (HttpStatus.Series.SERVER_ERROR, "5xx"); SERIES_VIEWS = Collections.unmodifiableMap (views);} private final ErrorProperties errorProperties / * * Create a new {@ code DefaultErrorWebExceptionHandler} instance. * @ param errorAttributes the error attributes * @ param resourceProperties the resources configuration properties * @ param errorProperties the error configuration properties * @ param applicationContext the current application context * / public DefaultErrorWebExceptionHandler (ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {super (errorAttributes, resourceProperties, applicationContext); this.errorProperties = errorProperties } @ Override protected RouterFunction getRoutingFunction (ErrorAttributes errorAttributes) {return route (acceptsTextHtml (), this::renderErrorView) .andRoute (all (), this::renderErrorResponse);} / * Render the error information as an HTML view. * @ param request the current request * @ return a {@ code Publisher} of the HTTP response * / protected Mono renderErrorView (ServerRequest request) {boolean includeStackTrace = isIncludeStackTrace (request, MediaType.TEXT_HTML); Map error = getErrorAttributes (request, includeStackTrace); HttpStatus errorStatus = getHttpStatus (error) ServerResponse.BodyBuilder responseBody = ServerResponse.status (errorStatus) .contentType (MediaType.TEXT_HTML) Return Flux .just ("error/" + errorStatus.value (), "error/" + SERIES_VIEWS.get (errorStatus.series ()), "error/error") .flatMap ((viewName)-> renderErrorView (viewName, responseBody) Error) .switchIfEmpty (this.errorProperties.getWhitelabel (). IsEnabled ()? RenderDefaultErrorView (responseBody, error): Mono.error (getError (request)). Next ();} / * * Render the error information as a JSON payload. * @ param request the current request * @ return a {@ code Publisher} of the HTTP response * / protected Mono renderErrorResponse (ServerRequest request) {boolean includeStackTrace = isIncludeStackTrace (request, MediaType.ALL); Map error = getErrorAttributes (request, includeStackTrace) Return ServerResponse.status (getHttpStatus (error)) .contentType (MediaType.APPLICATION_JSON_UTF8) .body (BodyInserters.fromObject (error));} / * Determine if the stacktrace attribute should be included. * @ param request the source request * @ param produces the media type produced (or {@ code MediaType.ALL}) * @ return if the stacktrace attribute should be included * / protected boolean isIncludeStackTrace (ServerRequest request, MediaType produces) {ErrorProperties.IncludeStacktrace include = this.errorProperties .getIncludeStacktrace () If (include = = ErrorProperties.IncludeStacktrace.ALWAYS) {return true;} if (include = = ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {return isTraceEnabled (request);} return false } / * Get the HTTP error status information from the error map. * @ param errorAttributes the current error information * @ return the error HTTP status * / protected HttpStatus getHttpStatus (Map errorAttributes) {int statusCode = (int) errorAttributes.get ("status"); return HttpStatus.valueOf (statusCode);} / * * Predicate that checks whether the current request explicitly support * {@ code "text/html"} media type. *

* The "match-all" media type is not considered here. * @ return the request predicate * / protected RequestPredicate acceptsTextHtml () {return (serverRequest)-> {try {List acceptedMediaTypes = serverRequest.headers () .accept (); acceptedMediaTypes.remove (MediaType.ALL); MediaType.sortBySpecificityAndQuality (acceptedMediaTypes) Return acceptedMediaTypes.stream () .anyMatch (MediaType.TEXT_HTML::isCompatibleWith);} catch (InvalidMediaTypeException ex) {return false }}

DefaultErrorWebExceptionHandler inherits AbstractErrorWebExceptionHandler; 's getRoutingFunction method to renderErrorView acceptsTextHtml, and others return error messages in json format through renderErrorResponse.

ExceptionHandlingWebHandler

SpringMyRose 5.1.7.RELEASEMAE sources.jarAccording to orgUnix springframeworkUniverse webbank serverhand handlerAccordExceptionHandlingWebHandler.java

Public class ExceptionHandlingWebHandler extends WebHandlerDecorator {private final List exceptionHandlers; public ExceptionHandlingWebHandler (WebHandler delegate, List handlers) {super (delegate); this.exceptionHandlers = Collections.unmodifiableList (new ArrayList (handlers));} / * * Return a read-only list of the configured exception handlers. * / public List getExceptionHandlers () {return this.exceptionHandlers;} @ Override public Mono handle (ServerWebExchange exchange) {Mono completion; try {completion = super.handle (exchange) } catch (Throwable ex) {completion = Mono.error (ex);} for (WebExceptionHandler handler: this.exceptionHandlers) {completion = completion.onErrorResume (ex-> handler.handle (exchange, ex));} return completion;}}

ExceptionHandlingWebHandler inherits WebHandlerDecorator and calls the handle method of WebExceptionHandler one by one.

Summary

ErrorWebFluxAutoConfiguration registered DefaultErrorAttributes and ErrorWebExceptionHandler.

DefaultErrorAttributes implements the ErrorAttributes interface, and its getErrorAttributes method returns information such as timestamp, path, status, error, message, exception (includeException), trace (includeStackTrace), etc. GetError method gets Throwable;storeErrorInformation from ServerRequest's ERROR_ATTRIBUTE and stores Throwable in ServerWebExchange's attributes

DefaultErrorWebExceptionHandler inherits AbstractErrorWebExceptionHandler; 's getRoutingFunction method to renderErrorView acceptsTextHtml, and others return error messages in json format through renderErrorResponse.

After reading the above, have you mastered the role of ErrorWebFluxAutoConfiguration in spring boot? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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

Internet Technology

Wechat

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

12
Report