webMvc exception handling of Spring

Exception handling can be either front-end or back-end.

From a safe point of view, both sides should be dealt with.

This paper focuses on how to handle http request exceptions on the server.

1, Common exception types

When we make an http request, there will be various possible errors, such as:

1. Service exceptions

2. The interface is abnormal, and there are all kinds of interface exceptions

The extreme is the exception of the interface.

Exceptions can occur in each step of the request. This mainly describes the normal situation of network communication.

These communication exceptions are in method org springframework. web. servlet. mvc. support. DefaultHandlerExceptionResolver. Doresolveexception (HttpServletRequest, httpservletresponse, object, exception)

Detailed description:

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

We organize it into tables:

code name remarks
 handleHttpRequestMethodNotSupported The request method is not supported For example, RequestMapping only specifies post, but uses get to request
 HttpMediaTypeNotSupportedException Media type not supported For example, the message converter may only process JSON, but the request header is set to xml and so on
 HttpMediaTypeNotAcceptableException Media type not acceptable The request processor was unable to generate response content that the client can support
 MissingPathVariableException Missing path variable

The request url is missing a path variable. for example

 @RequestMapping("/show/{name}")

 public Object show(@PathVariable String name){}

The Engineer may have written less {name}

 MissingServletRequestParameterException Missing Servlet request parameters For example, @ RequstParam is used, but the url does not provide the corresponding parameters
 ServletRequestBindingException Servlet request binding exception Exception that occurs when binding is executed
 ConversionNotSupportedException Unsupported conversion exception Cannot find a matching editor or converter for the bean
 TypeMismatchException Type mismatch exception When copying the bean, it is found that the type does not match
 HttpMessageNotReadableException The http message cannot be read When an error occurs in the HttpMessageConverter#read method
 HttpMessageNotWritableException http message cannot write exception When an error occurs in the HttpMessageConverter#write method
 MethodArgumentNotValidException Method parameter unavailable exception Exception occurred when validating @ Valid parameters
 MissingServletRequestPartException Missing Servlet request part exception The requested media type is a file type (or attachment), but the content is not
 BindException Binding exception  
 NoHandlerFoundException Processor not found

 By default when the DispatcherServlet can't find a handler for a request it sends a 404 response. However if its property "throwExceptionIfNoHandlerFound" is set to true this exception is raised and may be handled with a configured HandlerExceptionResolver.

By default, when the distributor processor program cannot find the requested processor (such as static resources or requesting controller methods), it will send a 404 response. In addition, the property throwExceptionIfNoHandlerFound=true will be set and no handler exception will be thrown. Users can consider configuring a HandlerExceptionResolver to handle

 AsyncRequestTimeoutException   Asynchronous request timeout exception. 503 error.

There are far more exception / error related classes in spring and springboot than in the above table.

Due to the rigorous requirements of the code, almost all functions / procedures will have try catch throw. Due to space limitation, it is not necessary to discuss all the codes.

 

2, Abnormal configuration in WMS

For the introduction of wms, please refer to: https://www.cnblogs.com/lzfhope/p/16103174.html

There are several places where wms can handle exceptions, but we specifically consider the part of the word exception.

 

@Bean
public HandlerExceptionResolver handlerExceptionResolver(
        @Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager) {
    List<HandlerExceptionResolver> exceptionResolvers = new ArrayList<>();
    configureHandlerExceptionResolvers(exceptionResolvers);
    if (exceptionResolvers.isEmpty()) {
        addDefaultHandlerExceptionResolvers(exceptionResolvers, contentNegotiationManager);
    }
    extendHandlerExceptionResolvers(exceptionResolvers);
    HandlerExceptionResolverComposite composite = new HandlerExceptionResolverComposite();
    composite.setOrder(0);
    composite.setExceptionResolvers(exceptionResolvers);
    return composite;
}

/**
 * Override this method to configure the list of
 * {@link HandlerExceptionResolver HandlerExceptionResolvers} to use.
 * <p>Adding resolvers to the list turns off the default resolvers that would otherwise
 * be registered by default. Also see {@link #addDefaultHandlerExceptionResolvers}
 * that can be used to add the default exception resolvers.
 * @param exceptionResolvers a list to add exception resolvers to (initially an empty list)
 */
protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
}



/**
 * A method available to subclasses for adding default
 * {@link HandlerExceptionResolver HandlerExceptionResolvers}.
 * <p>Adds the following exception resolvers:
 * <ul>
 * <li>{@link ExceptionHandlerExceptionResolver} for handling exceptions through
 * {@link org.springframework.web.bind.annotation.ExceptionHandler} methods.
 * <li>{@link ResponseStatusExceptionResolver} for exceptions annotated with
 * {@link org.springframework.web.bind.annotation.ResponseStatus}.
 * <li>{@link DefaultHandlerExceptionResolver} for resolving known Spring exception types
 * </ul>
 */
protected final void addDefaultHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers,
        ContentNegotiationManager mvcContentNegotiationManager) {

    ExceptionHandlerExceptionResolver exceptionHandlerResolver = createExceptionHandlerExceptionResolver();
    exceptionHandlerResolver.setContentNegotiationManager(mvcContentNegotiationManager);
    exceptionHandlerResolver.setMessageConverters(getMessageConverters());
    exceptionHandlerResolver.setCustomArgumentResolvers(getArgumentResolvers());
    exceptionHandlerResolver.setCustomReturnValueHandlers(getReturnValueHandlers());
    if (jackson2Present) {
        exceptionHandlerResolver.setResponseBodyAdvice(
                Collections.singletonList(new JsonViewResponseBodyAdvice()));
    }
    if (this.applicationContext != null) {
        exceptionHandlerResolver.setApplicationContext(this.applicationContext);
    }
    exceptionHandlerResolver.afterPropertiesSet();
    exceptionResolvers.add(exceptionHandlerResolver);

    ResponseStatusExceptionResolver responseStatusResolver = new ResponseStatusExceptionResolver();
    responseStatusResolver.setMessageSource(this.applicationContext);
    exceptionResolvers.add(responseStatusResolver);

    exceptionResolvers.add(new DefaultHandlerExceptionResolver());
}    

The exception handling mechanism can be overridden by the configureresponders method or the exception handling method.

But generally, we don't have that need.

Generally, you can use DefaultHandlerExceptionResolver for processing, which is the content described above.

3, http request exception of springboot

If you use springboot to develop, then springboot will introduce an org.org.org through automatic configuration springframework. boot. autoconfigure. web. servlet. error. BasicErrorController

This kind of controller class implements the interface org springframework. boot. web. servlet. error. ErrorController.

According to the description of springboot, we can implement its interface org springframework. boot. web. servlet. error. Errorcontroller to override the default implementation.

For example:

@Controller
public class ErrController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request,HttpServletResponse response) {
        int statusCode=response.getStatus();
        if (statusCode == 404) {
            return "/main/err.html";
        } 
        else  if (statusCode == 444) {
            return "/main/login.html";
        }
        return "";
    }
}

It should be noted that the code of ErrorController is executed after the exception handling of wms.

In addition, it can also be processed only with the advice annotation of the controller, for example: SpringBoot series - Custom unified exception handling - Huanzi qch - blog Garden (cnblogs.com)

 

4, Summary

spring also introduces a mechanism: verification in order to avoid problems in our code. For example, you can verify parameter validation. There are only a few exceptions that are not valid.

But generally, this verification is not required, because it is usually processed first on the client!

 

Tags: Spring MVC

Posted by flappy_warbucks on Mon, 16 May 2022 16:24:46 +0300