Skip to content

ExceptionHandlerExceptionResolver warns when re-throwing the exception cause #23233

@arlowhite

Description

@arlowhite

If an @ExceptionHandler method matches and rethrows a cause of the root exception, it will always log this warning. Instead, the warning should only be logged if the exception differs from the one bound to the ExceptionHandler method's parameter.

Instead, this code should do something like this:

        Throwable evaluatedException = null;
        try {
            if (logger.isTraceEnabled()) {
                logger.trace("Invoking @ExceptionHandler method: " + exceptionHandlerMethod);
            }
            Throwable cause = exception.getCause();
            if (cause != null) {
                // Expose cause as provided argument as well
                evaluatedException = cause;
                exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, cause, handlerMethod);
            }
            else {
                // Otherwise, just the given exception as-is
                evaluatedException = exception;
                exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, handlerMethod);
            }
        }
        catch (Throwable invocationEx) {
            // Any other than the original exception is unintended here,
            // probably an accident (e.g. failed assertion or the like).
            if (invocationEx != evaluatedException && logger.isWarnEnabled()) {
                logger.warn("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx);
            }
            // Continue with default processing of the original exception...
            return null;
        }

I'm testing on Spring 4.3.24, but the code appears to be the same.

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions