Custom exception springMVC & springCloud

A, springMVC custom exception handling

Abnormal thrown Controller centralized processing:

controller in the unusual 0/1

. 1  @Controller
 2 @RequestMapping ( "/ Test" )
 . 3  public  class TestController {
 . 4  
. 5  
. 6      / ** 
. 7       * Return Value prefix: prefix view resolver prefixes and suffixes will not be spliced
 . 8       * the redirect: Redirect
 9       * forward: forward request
 10       * @return 
. 11       * / 
12 is      @RequestMapping ( "/ testString" )
 13 is      public String testString () {
 14          System.out.println (1/0 );
 15          return "the redirect: testModelAndView" ;
 16      }
17 
18 
19 
20 
21 
22 
23 }

 

Exception class (analysis abnormal Resolve)

Specify a message back to the user-friendly

Specify a jump error.jsp

Programmers can look up anything unusual in the console


        ex.printStackTrace();
@Component
 public  class MyHandlerException the implements the HandlerExceptionResolver {
     / ** 
     * analysis abnormal 
     * @param Request request object 
     * @param Response Response 
     * @param Handler Processor 
     * @param EX captured exception object 
     * @return   model and view objects
      * / 
    @ override 
    public ModelAndView the resolveException (the HttpServletRequest Request, Response the HttpServletResponse, Object Handler, Exception EX) { 

        ex.printStackTrace (); 
        ModelAndView ModelAndView = new newModelAndView (); 
        modelAndView.addObject ( "the Message", "System error, please contact the administrator !!" ); 
        modelAndView.setViewName ( "error" ); 

        return ModelAndView; 
    } 
}

 

spring-mvc.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:mvc="http://www.springframework.org/schema/mvc"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7        http://www.springframework.org/schema/beans/spring-beans.xsd
 8        http://www.springframework.org/schema/context
 9        http://www.springframework.org/schema/context/spring-context.xsd
10        http://www.springframework.org/schema/mvc
11        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
12     <!--开启注解扫描-->
13     <context:component-scan base-package="com.example"></context:component-scan>
14 
15     <!--视图解析器-->
16     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
17         <property name="prefix" value="/WEB-INF/"></property>
18         <property name="suffix" value=".jsp"></property>
. 19      </ the bean>
 20 is      <- driving MVC annotation:! Automatic loading processing mapping processing adapter ->
 21 is      <MVC: Annotation-Driven> </ MVC: Annotation-Driven>
 22 is </ Beans>

 

error.jsp in the WEB-INF

<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${message}
</body>
</html>

 

 

 

Second, custom exception handling springcloud

Background problem

Code redundancy, try-catch too many inappropriate.

Bad user experience, such as user operation returns '' operation failed '', it is unclear what specific abnormalities

solve

All global exception handler catches the exception (@ControllerAdvice), after capturing two cases:

 

1. custom exception (CustomerException) shall not inherit Exception, because there are invasive code, but also to continue to throw, so the inheritance RunTimeException,

2. unpredictable abnormal system level (a null pointer, connection timeout ...), abnormal class as a key, value friendly information.

If the query did not return exception class specific information in the map, if the exception class key in the map is present, the return value prompt.

(A) Examples of custom exception

1- execution order "in a thrown 4CustomerException class 2 -" is caught 3, in particular 3 to handle this exception handler, acquires the abnormality information returned to the user-specific information.

1 anomalies

ExceptionCast.cast(Code.EXIT)。

2ExceptionCast class (class exception is thrown) and
3ExceptionCatch (crawl type)
1 public class ExceptionCast {
2 public static void cast(ResultCode resultCode){
3     throw new CustomerException(resultCode);
4 
5 }
6 
7 
8 }
 1 @ControllerAdvice
 2 @Slf4j
 3 public class ExceptionCatch {
 4     @ExceptionHandler(CustomerException.class)
 5     public ResponseResult customerException(CustomerException customerException){
 6 
 7         ResultCode resultCode = customerException.getResultCode();
 8         ResponseResult responseResult = new ResponseResult(resultCode);
 9     return  responseResult;
10     }

 

4CustomerException类(抛出的异常类)
public class CustomerException extends RuntimeException {
    private ResultCode resultCode;
    public ResultCode getResultCode(){
        return resultCode;

    }
    public CustomerException(ResultCode resultCode){
        super("错误代码"+resultCode.code()+"错误信息:"+resultCode.message());
        this.resultCode =resultCode;

    }
}

(二)系统级别的例子

抓取不可预知的异常,信息用log输出,

@Slf4j

后期方便定位问题,info。warning,error日志的常见级别

 1 @ControllerAdvice
 2 @Slf4j
 3 public class ExceptionCatch {
 4  
 5 @ExceptionHandler(Exception.class)
 6     public ResponseResult exception(Exception exception){
 7         log.error(exception.getMessage());
 8         return null;
 9 
10 }
11 
12 }

特定异常添加到特定map中(谷歌提供的)

ImmutableMap
//全局异常抓取类
@ControllerAdvice //增强controller
@Slf4j
public class ExceptionCatch {

    //ImmutableMap 线程安全,声明之后内容不可变
    private static ImmutableMap<Class<? extends Throwable>,ResultCode> EXCEPTIONS;

    protected static ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder = ImmutableMap.builder();

    //抓取自定义异常(可预知异常)
    @ExceptionHandler(CustomerException.class)
    @ResponseBody
    public ResponseResult customerException(CustomerException customerException){
        //给用户返回友好信息
        ResultCode resultCode = customerException.getResultCode();

        ResponseResult responseResult = new ResponseResult(resultCode);
        return responseResult;
    }

    //抓取不可预知异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception exception){

        log.error(exception.getMessage());

        if (EXCEPTIONS == null){
            EXCEPTIONS = builder.build();
        }
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if (resultCode == null){
            return new ResponseResult(CommonCode.SERVER_ERROR);
        }else{
            return new ResponseResult(resultCode);
        }

    }

    static {
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALIDATE_PARAMS);
    }
}

从map中找,有,返回key对应的value,没有的话返回固定的友好提示:服务器繁忙。

Guess you like

Origin www.cnblogs.com/fengtangjiang/p/11111200.html