下面代码可直接拷在项目内运行即可,MessageResult类为一个统一返回类
/**
* 自定义异常处理器
*
* @author 问梦杀帝
*
*/
@RestControllerAdvice
public class ExceptionController {
private static final Logger log = LoggerFactory.getLogger(ExceptionController.class);
MessageResult<String> result = new MessageResult<String>();
/**
* 请求方式不支持
*/
@ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
public MessageResult<String> handleException(HttpRequestMethodNotSupportedException e) {
log.error(e.getMessage(), e);
result.setResultCode(500);
result.setResultMessage("不支持' " + e.getMethod() + "'请求");
return result;
}
/**
* 拦截未知的运行时异常
*/
@ExceptionHandler(RuntimeException.class)
public MessageResult<String> notFount(RuntimeException e) {
log.error("运行时异常:", e);
result.setResultCode(500);
result.setResultMessage("运行时异常:" + e.getMessage());
return result;
}
/**
* 系统异常
*/
@ExceptionHandler(Exception.class)
public MessageResult<String> handleException(Exception e) {
log.error(e.getMessage(), e);
result.setResultCode(500);
result.setResultMessage("服务器错误,请联系管理员");
return result;
}
}