您的位置:首页 > 编程语言 > Java开发

SpringMvc全局异常统一处理

2018-12-26 15:17 204 查看
版权声明:如若转载,请说明出处哦,谢谢! https://blog.csdn.net/a823007573/article/details/85262547

全局异常处理还是基于AOP的思想,在SpringMvc中实现起来很简单,参照如下代码,其中的Resp是自定义的统一响应格式类,可自行设计,RespType是自定义的响应信息常量。

注意:该类所在的包必须被spring扫描到容器中。

[code]/**
* 统一异常处理
*/
@RestControllerAdvice
public class ControllerExceptionHandler {

private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public Resp<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
logger.error("请求参数读取错误", e);
return new Resp<String>().error(RespType.BAD_REQUEST);
}

/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({MethodArgumentNotValidException.class})
public Resp<String> handleValidationException(MethodArgumentNotValidException e) {
logger.error("请求参数验证失败", e);
return new Resp<String>().error(RespType.BAD_REQUEST);
}

/**
* 405 - Method Not Allowed。HttpRequestMethodNotSupportedException
* 是ServletException的子类,需要Servlet API支持
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Resp<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
logger.error("请求方法不支持", e);
return new Resp<String>().error(RespType.METHOD_NOT_ALLOWED);
}

/**
* 415 - Unsupported Media Type。HttpMediaTypeNotSupportedException
* 是ServletException的子类,需要Servlet API支持
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler({HttpMediaTypeNotSupportedException.class})
public Resp<String> handleHttpMediaTypeNotSupportedException(Exception e) {
logger.error("content-type类型不支持", e);
return new Resp<String>().error(RespType.UNSUPPORTED_MEDIA_TYPE);
}

/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Resp<String> handleException(Exception e) {
logger.error("服务器内部错误", e);
return new Resp<String>().error(RespType.INTERNAL_SERVER_ERROR);
}

}

代码参照了 书呆子Rico 的文章 REST风格框架实战:从MVC到前后端分离(附完整Demo)

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: