Spring boot/Spring 统一错误处理方案的使用

10,032 阅读5分钟

当我们开发spring web应用程序时,对于如IOException,ClassNotFoundException之类的检查异常,往往编译器会提示程序员采用try-catch进行显式捕获,而对于像ClassCastException,NullPointerException这类非检查异常,编译器是不会提示你了,这往往也是能体现程序员代码编写能力的一个方面。

在spring web特别是spring-boot应用中,当一个请求调用成功时,一般情况下会返回json格式的对象,就像下面图所示:

但如果请求抛出了一个RuntimeException呢?如果我们不做处理,再次调用时将出现下面的页面:

也就是说当调用出现错误时,spring-boot默认会将请求映射到/error路径中去,如果没有相应的路径请求处理器,那么就会返回上面的Whitelabel错误页面。

1、自定义错误处理页面

当然对运行时异常不做处理是不可能的啦!通常的做法是自定义统一错误页面,然后返回。按照上面的思路,我们实现一个请求路径为/error的控制器,控制器返回一个资源路径地址,定义请求映射路径为/error的控制器并实现ErrorController接口,代码如下:

MyErrorPageController

package com.example.demo.controller.handler.errorpage;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 
 * The class MyErrorPageController.
 *
 * Description:自定义错误页面
 *
 * @author: huangjiawei
 * @since: 2018年6月13日
 * @version: $Revision$ $Date$ $LastChangedBy$
 *
 */
@Controller
public class MyErrorPageController implements ErrorController {
    
    @RequestMapping("/error")
    public String handleError() {
    	return "error.html"; // 该资源位于resources/static目录下
    }
    
    @Override
    public String getErrorPath() {
    	return null;
    }
}

然后在reosurces/static目录下建立error.html文件:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>这是个错误页面!存放在resources/static目录下,spring-boot发生错误时默认调用</h1>
</body>
</html>

再次请求http://localhost:7000/demo/getUserInfoWithNoHandler.json,如下:

2、使用@ControllerAdvice@ResponseBody@ExceptionHandler统一处理异常

在spring中可以使用上面3个注解进行统一异常处理,默认情况下我们可以针对系统中出现的某种类型的异常定义一个统一的处理器handler,比如说系统抛出了一个NullPointerException,那么我们可以定义一个专门针对NullPointerException的处理器,代码如下:

getUserInfoWithNullPointerException接口

/**
 * 测试空指针错误的处理
 * @return
 * @throws NullPointerException
 */
@RequestMapping(value = "getUserInfoWithNullPointerException.json", method = RequestMethod.GET)
public Student getUserInfoWithNullPointerException() throws NullPointerException {
	throw new NullPointerException();
}

NullPointerExceptionHandler.java

package com.example.demo.controller.handler;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.pojo.ErrorReturn;

/**
 * 
 * The class NullPointerExceptionHandler.
 *
 * Description:处理空指针
 *
 * @author: huangjiawei
 * @since: 2018年6月13日
 * @version: $Revision$ $Date$ $LastChangedBy$
 *
 */
@ControllerAdvice
public class NullPointerExceptionHandler {
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ErrorReturn dealNullPointerException() {
        e.printStackTrace();
    	ErrorReturn error = new ErrorReturn();
    	error.setReturnCode("-1");
    	error.setDesc("出现空指针异常啦!");
    	return error;
    }
}

浏览器执行:http://localhost:7000/demo/getUserInfoWithNullPointerException.json

同样的道理,如果我们还需要为其他的运行时异常提供统一的处理器,那么也可以像上面一样为每一个异常类型定义一个处理器,比如我们又想为ArithmeticException定义处理器,那么我们只需要建立一个类或者方法,然后在方法上的@ExceptionHanler注解内加上ArithmeticException.class指定异常类型即可。

不过你有没有发现,这样为每种异常类型定义一个异常处理类或者方法,因为运行时异常类型特别多,不可能为每种类型都指定一个处理器类或方法,针对这种情况,spring也是可以解决的。如果我们没有为某种特定类型异常,如ArithmeticException定义处理器,那么我们可以定义一个Exception或者Throwable处理器统一处理。

这样做的好处是,减少了处理器类的数量,同时将异常处理转移到父类上面去,这也是继承的一大优势吧!但是,当你既定义了特定类型的异常,同时又定义了Exception异常的处理器,那么要小心了,这里不一定有优先级的关系,也就是说不一定会出现只执行父异常处理器的情况,可能是只执行A处理器,而不执行B处理器或者只执行B处理器,不执行A处理器。如NullPointerExceptionHandler异常会向Exception异常传递(但ArithmeticException不会向Exception传递)

现在假设我们既定义上面的NullPointerExceptionHandler,又定义了下面的ExceptionThrowableHandler,那么当发生NullPointerException时,就会默认执行ExceptionThrowableHandler的方法。

ExceptionThrowableHandler.java

package com.example.demo.controller.handler;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.pojo.ErrorReturn;

/**
 * 
 * The class ExceptionThrowableHandler.
 *
 * Description:有些异常会向高级别异常传递(但ArithmeticException不会向Exception传送)
 *
 * @author: huangjiawei
 * @since: 2018年6月13日
 * @version: $Revision$ $Date$ $LastChangedBy$
 *
 */
@ControllerAdvice
public class ExceptionThrowableHandler {
    
    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public ErrorReturn dealThrowable() {
    	ErrorReturn error = new ErrorReturn();
    	error.setDesc("处理Throwable!");
    	error.setReturnCode("-1");
    	return error;
    }
    
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ErrorReturn dealCommonException() {
    	ErrorReturn error = new ErrorReturn();
    	error.setReturnCode("-1");
    	error.setDesc("公共异常处理!");
    	return error;
    }
}

浏览器执行 : http://localhost:7000/demo/getUserInfoWithNullPointerException.json

可以发现只执行Exception的处理器,没有执行空指针的处理器,也就是异常处理往上传送了。下面再来看看抛出ArithmeticException的情况:

getUserInfoWithArithmeticException.json

/**
 * 测试ArithmeticException错误的处理
 * @return
 * @throws ArithmeticException
 */
@RequestMapping(value = "getUserInfoWithArithmeticException.json", method = RequestMethod.GET)
public Student getUserInfoWithArithmeticException() throws ArithmeticException {
	throw new ArithmeticException();
}

ArithmeticExceptionHandler.java

package com.example.demo.controller.handler;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.pojo.ErrorReturn;

@ControllerAdvice
public class ArithmeticExceptionHandler {
    /**
     * 处理ArithmeticException异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ArithmeticException.class)
    public ErrorReturn dealArithmeticException() {
    	ErrorReturn errorObject = new ErrorReturn();
    	errorObject.setReturnCode("-1");
    	errorObject.setDesc("算数处理出现异常!");
    	return errorObject;
    }
}

浏览器执行 : http://localhost:7000/demo/getUserInfoWithArithmeticException.json

结果发现异常处理并没有往上层的ExceptionHandler传送。

总结:对于既定义特定类型的处理器,又定义Exception等父类型的处理器时要特别小心,并不是所有的异常都会往上级处理,如果我们想只减少处理器类的数量,不想为每种特定类型的处理器添加类或者方法,那么小编建议使用instanceof关键字对异常类型进行判断即可。

如下面的代码,我们只建立一个公共的异常处理器,处理Exception异常,同时使用instanceof进行判断。

@ExceptionHandler(Exception.class)
@ResponseBody
public ErrorReturn dealCommonException(Exception e) {
    ErrorReturn error = new ErrorReturn();
    // 此处可以采用 instanceof 判断异常类型
    if (e instanceof ArithmeticException) {
    	error.setReturnCode("-1");
    	error.setDesc("算数异常处理!");
    	return error;
    }
    System.err.println("exception");
    error.setReturnCode("-1");
    error.setDesc("公共异常处理!");
    return error;
}

浏览器执行抛出ArithmeticException的接口,如下:

本文代码地址: github.com/SmallerCode…

谢谢阅读,欢迎start,指正!