web项目中的RuntimeException需要处理

1. 提出问题

Java的Exception分为两大类,RuntimeException和非RuntimeException,这个应该基本都知道。
我们经常看到说,RuntimeException和Error属于未检查异常(unchecked),Java编译器在运行程序之前无法发现这样的异常,所以不需要捕获。

这样做有时候其实是不合适的

web程序中为了接口返回值的一致性,必须对RuntimeException做处理。举例:
controller类

@RestController
@RequestMapping(value = "test")
public class TestController {

    private final Logger log = LoggerFactory.getLogger(TestController.class);

    @Autowired
    TestExceptionService testExceptionService;

    @ApiOperation(value = "Exception测试接口")
    @RequestMapping(value = "/exception", method = RequestMethod.POST)
    public String exception() {
        log.info("测试Exception");
        ResultUtils result = new ResultUtils();
    try {
            testExceptionService.testException();
            result.setData("测试普通Exception成功");
        } catch (Exception e) {
            result.setData(e.getMessage());
        }
        return JSONObject.toJSONString(result);
    }

    @ApiOperation(value = "RuntimeException测试接口")
    @RequestMapping(value = "/runtimeException", method = RequestMethod.POST)
    public String runtimeException() {
        log.info("测试RuntimeException");
        testExceptionService.testRuntimeException();
        ResultUtils result = new ResultUtils();
        result.setData("测试RuntimeException");
        return JSONObject.toJSONString(result);
    }
}

Service类

public class TestExceptionService {
  // 显式地抛出普通的Excption
    public void testException() throws Exception {
        throw new Exception("发生了普通Exception");
    }
  //RuntimeException不需要显式地抛出,但是外界是可以catch地
    public void testRuntimeException() {
        throw new RuntimeException("发生了RuntimeException");
    }
}

ResultUtils是自己定义的,与接口返回Json参数结构相同的类,访问http://ip:port/test/exception,得到:

{
    "code": "0",
    "data": "发生了普通Exception",
    "message": "操作成功",
    "pageNum": 0,
    "pageSize": 0,
    "pages": 0,
    "total": 0
}

访问http://ip:port/test/runtimeException,得到:

{
    "timestamp": "2019-06-04T05:43:40.764+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "发生了RuntimeException",
    "path": "/test/runtimeException"
}

很明显,普通Exception测试中,catch了Exception类对返回结果做了处理;而发生了RuntimeException的类中,这时候是spring自己处理了RuntimeException,这样的数据返回给前端很有可能会造成解析失败(你也可以让前端对这种消息都做特殊处理)。

2. 解决问题

显然,因为RuntimeException虽然是特殊的Exception,但是仍然是Exception,虽然没有显式抛出,但是我们是可以catch的,controller的RuntimeException测试代码修改一下

@ApiOperation(value = "RuntimeException测试接口")
    @RequestMapping(value = "/runtimeException", method = RequestMethod.POST)
    public String runtimeException() {
        log.info("测试RuntimeException");
        ResultUtils result = new ResultUtils();
        try {
            testExceptionService.testRuntimeException();
            result.setData("测试RuntimeException成功");
        }catch (Exception e) {
            result.setData(e.getMessage());
        }
        return JSONObject.toJSONString(result);
    }

此时再访问http://ip:port/test/runtimeException,得到:

{
    "code": "0",
    "data": "发生了RuntimeException",
    "message": "操作成功",
    "pageNum": 0,
    "pageSize": 0,
    "pages": 0,
    "total": 0
}

3. 更好的方法

更常见的做法是,加一个异常处理类

@RestControllerAdvice
public class RestfulExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(RestfulExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public String controllerExceptionHandler(Exception ex) {
        ResultUtils result = new ResultUtils();
        result.setCode("1");
        result.setData(ex.getMessage());
        log.error("errorCode:{}\n errorMessage:\n", result.getCode(), ex);
        return JSON.toJSONString(responseVO);
    }
}

所有Exception(显式抛出的Exception和RuntimeException)都会经过这个类处理,将RuntimeException代码还原,测试一下,再访问http://ip:port/test/runtimeException,得到:

{
    "code": "1",
    "data": "发生了RuntimeException",
    "message": "操作成功",
    "pageNum": 0,
    "pageSize": 0,
    "pages": 0,
    "total": 0
}

很明显,code是1,说明确实是RestfulExceptionHandler给出的返回值。


结束。

转载于:https://www.jianshu.com/p/9f350c9eae3b

猜你喜欢

转载自blog.csdn.net/weixin_34346099/article/details/91271512