新建异常实体类信息
public class AjaxResult extends HashMap<String, Object>{
/**
* 返回消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static AjaxResult conflict(String code,String msg, Object data,HttpServletResponse response)
{
response.setStatus(HttpStatus.CONFLICT);
return new AjaxResult(code, msg, data);
}
/**
* 返回消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult conflict(String code,String msg,HttpServletResponse response)
{
response.setStatus(HttpStatus.CONFLICT);
return new AjaxResult(code,msg, null);
}
/**
* 返回消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult conflict(String msg,HttpServletResponse response)
{
response.setStatus(HttpStatus.CONFLICT);
return new AjaxResult("conflict",msg);
}
}
自定义异常类型
比如定义一个操作异常,继承运行时异常
public final class OperateException extends RuntimeException
{
private static final long serialVersionUID = 1L;
/**
* 错误码
*/
private Integer code;
/**
* 错误提示
*/
private String message;
/**
* 错误明细,内部调试错误
*/
private String detailMessage;
/**
* 空构造方法,避免反序列化问题
*/
public OperateException()
{
}
public OperateException(String message)
{
this.message = message;
}
public OperateException(String message, Integer code)
{
this.message = message;
this.code = code;
}
public String getDetailMessage()
{
return detailMessage;
}
@Override
public String getMessage()
{
return message;
}
public Integer getCode()
{
return code;
}
public OperateException setMessage(String message)
{
this.message = message;
return this;
}
public OperateException setDetailMessage(String detailMessage)
{
this.detailMessage = detailMessage;
return this;
}
}
实现全局异常处理器
这里用到一个注解***@RestControllerAdvice***
@ExceptionHandler(OperateException.class)方法上写上要处理的自定义异常类
@RestControllerAdvice
public class GlobalExceptionHandler
{
/**
* 拦截操作异常
*/
@ExceptionHandler(OperateException.class)
public AjaxResult handleOperateException(RuntimeException e, HttpServletRequest request,HttpServletResponse response)
{
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生操作异常.", requestURI, e);
return AjaxResult.conflict(e.getMessage(),response);
}
}
可以在使用时抛出
throw new OperateException("操作异常");