全局异常配置只须要添加一个全局的类便可,即配置全局异常Handler。java
@ControllerAdvice注解是用来配置控制器通知的,能够配置过滤拦截具体一种或者多种类型的注解,添加annotations属性便可,json
@ExceptionHandler注解用来配置须要拦截的异常类型,默认是全局类型。@ResponseStatus注解用于配置遇到该异常后返回数据时的StatusCode的值,这里默认使用值500。在类的上方配置了@ControllerAdvice的annotations属性值为RestController.class,也就是只有添加了@RestController注解的控制器才会进入全局异常处理。服务器
RestExceptionHandler全局处理类代码以下所示:spa
/** * @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:code
{ "status": -1, "message": "服务器繁忙,请稍后再试", "data": null }