1.创建BaseException类继承RuntimeException类
public class BaseException extends RuntimeException {
public BaseException() {
}
public BaseException(String msg) {
super(msg);
}
}
2.创建GlobalExceptionHandler类(里面引用了自定义的异常常量)
/**
* 全局异常处理器,处理项目中抛出的业务异常
*/
@RestControllerAdvice//在类上使用@RestControllerAdvice标记其为全局异常处理器
@Slf4j
public class GlobalExceptionHandler {
/**
* 捕获业务异常
* @param ex
* @return
*/
@ExceptionHandler
public Result exceptionHandler(BaseException ex){
log.error("异常信息:{}", ex.getMessage());
return Result.error(ex.getMessage());
}
/**
* SQL异常:用户重复添加...
* @param ex
* @return
*/
@ExceptionHandler
public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
log.error("异常信息:{}", ex.getMessage());
//异常信息:Duplicate entry '小智' for key 'employee.idx_username'
String message = ex.getMessage();
if (message.contains("Duplicate entry")) {
String[] split = message.split(" ");
String name = split[2];
String msg = name + MessageConstant.ALREADY_EXISTS;
return Result.error(msg);
} else {
return Result.error(MessageConstant.UNKNOWN_ERROR);
}
}
}
3.创建自定义异常(可以没有)
public class TestException extends BaseException{
public TestException(String msg) {
super(msg);
}
}
4.在业务中使用(try-catch代码块)
throw new TestException("测试异常成功!");