全局异常配置只需要添加一个全局的类即可,即配置全局异常Handler。
使用@ControllerAdvice
@ControllerAdvice注解是用来配置控制器通知的,可以配置过滤拦截具体一种或者多种类型的注解,添加annotations属性即可,
@ExceptionHandler注解用来配置需要拦截的异常类型,默认是全局类型。@ResponseStatus注解用于配置遇到该异常后返回数据时的StatusCode的值,这里默认使用值500。在类的上方配置了@ControllerAdvice的annotations属性值为RestController.class,也就是只有添加了@RestController注解的控制器才会进入全局异常处理。
RestExceptionHandler全局处理类代码如下所示:
/**
* @author cherrish
* @time 2018-08-12 11:29
* @name RestExceptionHandler
* @desc: result 异常统一处理
*/
@ControllerAdvice(annotations = RestController.class)
@ResponseBody
@Slf4j
public class RestExceptionHandler {
@ExceptionHandler
@ResponseStatus
public RestResp runtimeExceptionHandler(Exception e){
log.error("Runtime exception: ", e.getMessage(),e);
return RestResp.fail("服务器繁忙,请稍后再试!",null);
}
}
返回数据格式RestResp:
{
"status": -1,
"message": "服务器繁忙,请稍后再试",
"data": null
}