要将自己的系统异常进行细分,具体是业务异常还是其他什么异常
@ControllerAdvice
public class ExceptionController {
/**
* 日志对象
*/
private final Logger logger = LoggerFactory.getLogger(getClass());
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new DateEditor());
}
/**
* 无授权异常处理
* @return 授权异常
*/
@ExceptionHandler({UnauthenticatedException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public Object unauthorizedException(Exception e) {
logger.error("ExceptionHandler:"+e.getMessage(),e);
return handleExcetion(e);
}
/**
* 登录异常处理
* @return 登录异常
*/
@ExceptionHandler({ShiroException.class})
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
@ResponseBody
public Object shiroException(ShiroException e) {
logger.error("ExceptionHandler:"+e.getMessage(),e);
return handleExcetion(e);
}
/**
* 用于处理异常的
* @return 业务异常
*/
@ExceptionHandler({AdderBusinessException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Object businessException(AdderBusinessException e) {
logger.error("ExceptionHandler:"+e.getMessage(),e);
return handleExcetion(e);
}
/**
* 用于处理异常的
* @return 无服务异常
*/
@ExceptionHandler({NoHandlerFoundException.class})
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public Object notFoundException(NoHandlerFoundException e) {
logger.error("ExceptionHandler:"+e.getMessage(),e);
return handleExcetion(e);
}
/**
* 用于处理异常的
* @return 业务异常
*/
@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ResponseBody
public Object methodNotSupportException(HttpRequestMethodNotSupportedException e) {
logger.error("ExceptionHandler:"+e.getMessage(),e);
return handleExcetion(e);
}
/**
* 用于处理异常的
* @return 系统异常
*/
@ExceptionHandler({RuntimeException.class,Exception.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Object systemException(Exception e) {
logger.error("ExceptionHandler:"+e.getMessage(),e);
return handleExcetion(e);
}
protected Map<String,Object> handleExcetion(Exception e){
Map<String,Object> rs = new HashMap<>();
rs.put("message",e.getMessage());
rs.put("class",e.getClass().getName());
return rs;
}
}
使用@InitBinder,日期编辑器兼容日期,时间和日期时间三种类型
public class DateEditor extends PropertyEditorSupport {
private boolean allowEmpty = true;
/**
* 构造方法
*/
public DateEditor() {
}
/* (non-Javadoc)
* @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
*/
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (this.allowEmpty && !StringUtils.hasText(text)) {
setValue(null);
return;
}
if(NumberUtils.isNumber(text)){
setValue(new Date(Long.parseLong(text)));
}else{
setValue(null);
}
}
public String getJavaInitializationString() {
Date value = (Date) getValue();
return value != null?value.getTime() + "L":"null";
}
}
网友评论