@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
/**
* 处理数据库相同数据异常
* @param ex
* @return
*/ @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
if(ex.getMessage().contains("Duplicate entry")){
String[] split = ex.getMessage().split(" ");
String msg = split[2] + "已存在";
return R.error(msg);
}
return R.error("未知错误");
}
/**
* 处理自定义的业务异常
* @param ex
* @return
*/
@ExceptionHandler(ServiceException.class)
public R<String> exceptionHandler(ServiceException s) {
return R.error(s.getMessage());
}
}
自定义的业务异常ServiceException代码
public class ServiceException extends RuntimeException{
public ServiceException(String message){
super(message);
}
}
评论