Back to Javatutorial

Spring MVC 쳣

docs/Spring全家桶/SpringMVC/SpringMVC中的异常处理器.md

1.0.05.8 KB
Original Source

Spring MVC 쳣

2018-07-26 14:32

SpringĴ쳣HandlerExceptionResolverӿڵʵִָйгֵ쳣ij̶ֳϽHandlerExceptionResolverwebӦweb.xmlļܶ쳣ӳ䣨exception mapping񣬲Ⱥṩ˸ķʽṩ쳣׳ʱִеĸϢңһprogrammatic쳣ʽΪṩѡʹֱתһURL֮ǰʹServlet淶쳣ӳһģиķʽ쳣

<section>

ʵHandlerExceptionResolverӿڲʵ쳣ΨһʽֻṩresolveException(Exception, Hanlder)һʵֶѣ᷵һModelAndView֮⣬㻹ԿṩSimpleMappingExceptionResolver쳣ע@ExceptionHandler``SimpleMappingExceptionResolverȡ׳쳣֣ӳ䵽һͼȥServlet APIṩ쳣ӳǹܵȼ۵ģҲԻڴʵȸϸ쳣ӳ䡣@ExceptionHandlerעķ쳣׳ʱԴ쳣ķԶ@ControllerעĿҲԶ@ControllerAdviceУ߿ʹ쳣Ӧõ@ControllerСһСڽṩΪϸϢ

</section>

Spring MVC ʹ@ExceptionHandlerע

2018-07-26 14:33

<section>

HandlerExceptionResolverӿԼSimpleMappingExceptionResolverʵʹʽؽ쳣ӳ䵽ضͼϣ쳣תforwardӦͼǰʹJavaЩжϺ߼һЩر@ResponseBodyӦͼƵij£ֱӦ״̬벢ͻҪĴϢֱдӦУǸķ

Ҳʹ@ExceptionHandler@ExceptionHandlerڿڲģôղɿκࣩе@RequestMapping׳쳣㽫@ExceptionHandler``@ControllerAdviceУôᴦؿ׳쳣Ĵչʾһڿڲ@ExceptionHandler

@Controller
public class SimpleController {

    // @RequestMapping methods omitted ...

    @ExceptionHandler(IOException.class)
    public ResponseEntity<String> handleIOException(IOException ex) {
        // prepare responseEntity
        return responseEntity;
    }

}

@ExceptionHandlerע⻹Խһ쳣͵Ϊֵ׳б쳣ôӦ@ExceptionHandlerᱻáûиעκβֵôĬϴ쳣ͽǷЩ쳣

׼Ŀ@RequestMappingע⴦һ@ExceptionHandlerķͷֵҲԺ磬Servlet·ԽHttpServletRequestPortlet·ԽPortletRequestֵString͡»ᱻΪͼModelAndView͵ĶҲResponseEntity㻹ڷ@ResponseBodyעʹϢתתϢΪض͵ݣȻдصӦС

</section>

Spring MVC һ쳣

2018-07-26 14:34

ĹУSpring MVCܻ׳һЩ쳣SimpleMappingExceptionResolverԸҪܷؽκ쳣ӳ䵽һĬϵĴͼͻͨԶӦķʽַ쳣ģô˾ҪΪӦöӦ״̬롣׳쳣ͲͬҪòͬ״̬ʶǿͻ˴4xxǷ˴5xx

<section>

Ĭϴ쳣DefaultHandlerExceptionResolverὫSpring MVC׳쳣תɶӦĴ״̬롣ýMVCռûMVC JavaõķʽĬѾעˣ⣬ͨDispatcherServletעҲǿеģʹMVCռJava̷ʽõʱ򣩡±г˸ýܴһЩ쳣ǶӦ״̬롣

HTTP״̬
BindException400 (Ч)
ConversionNotSupportedException500 (ڲ)
HttpMediaTypeNotAcceptableException406 ()
HttpMediaTypeNotSupportedException415 (ֵ֧ý)
HttpMessageNotReadableException400 (Ч)
HttpMessageNotWritableException500 (ڲ)
HttpRequestMethodNotSupportedException405 (ֵ֧ķ)
MethodArgumentNotValidException400 (Ч)
MissingServletRequestParameterException400 (Ч)
MissingServletRequestPartException400 (Ч)
NoHandlerFoundException404 (δҵ)
NoSuchRequestHandlingMethodException404 (δҵ)
TypeMismatchException400 (Ч)
MissingPathVariableException500 (ڲ)
NoHandlerFoundException404 (δҵ)

´롣

The DefaultHandlerExceptionResolver works transparently by setting the status of the response. However, it stops short of writing any error content to the body of the response while your application may need to add developer- friendly content to every error response for example when providing a REST API. You can prepare a ModelAndView and render error content through view resolution?--?i.e. by configuring a ContentNegotiatingViewResolver, MappingJackson2JsonView, and so on. However, you may prefer to use@ExceptionHandler methods instead.

If you prefer to write error content via @ExceptionHandler methods you can extend ResponseEntityExceptionHandler instead. This is a convenient base for @ControllerAdvice classes providing an @ExceptionHandler method to handle standard Spring MVC exceptions and return ResponseEntity. That allows you to customize the response and write error content with message converters. See the ResponseEntityExceptionHandler javadocs for more details.

</section>

Spring MVC ʹ@ResponseStatusעҵ쳣

2020-07-31 10:52

ҵ쳣ʹ@ResponseStatusע⡣쳣׳ʱResponseStatusExceptionResolverӦӦ״̬롣DispatcherServletĬעһResponseStatusExceptionResolver Թʹá

ResponseStatusעʹ÷dz򵥣Ǵһ쳣࣬ע

package com.zj.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="ûƥ")
public class UserNotMatchException extends RuntimeException{
}

ResponseStatusע ԣvaluehttp״̬룬404500ȡreasonǴϢ

дһĿ귽׳쳣

@RequestMapping("/testResponseStatus")
public String testResponseStatus(int i){
    if(i==0)
        throw new UserNotMatchException();
    return "hello";
}

ʹResponseStatusע֮û쳣Լ쳣һûĴ롣

Spring MVC ServletĬҳĶƻ

2018-07-26 14:36

Ӧ״̬뱻Ϊ״̬룬ӦûʱServletͨȾһHTMLҳҪĬṩĴҳweb.xmlжһҳ<error-page>ԪءServlet 3淶֮ǰôҳԪر뱻ʽָӳ䵽һĴһ쳣͡Servlet 3ʼҳҪӳ䵽ϢˣζţָλþǶServletĬϴҳԶˡ

<section>
<error-page>
    <location>/error</location>
</error-page>

ҳλڿһJSPҳ棬һЩURLֻҪָһ@ControllerµĴ

дHttpServletResponseĴϢʹ״̬ڿͨȡ

@Controller
public class ErrorController {

    @RequestMapping(path = "/error", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Map<String, Object> handle(HttpServletRequest request) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", request.getAttribute("javax.servlet.error.status_code"));
        map.put("reason", request.getAttribute("javax.servlet.error.message"));

        return map;
    }

}

JSPôʹ:

<%@ page contentType="application/json" pageEncoding="UTF-8"%>
{
    status:<%=request.getAttribute("javax.servlet.error.status_code") %>,
    reason:<%=request.getAttribute("javax.servlet.error.message") %>
}
</section>