自定义全局异常处理器,捕获项目中抛出的异常,并将异常信息返回个前端。
关键在于@ExceptionHandler这个注解
@RestControllerAdvice
public class GlobalExceptionHandler {/*** 捕获业务异常* @param ex* @return*/
@ExceptionHandler
public Result exceptionHandler(BaseException ex){log.error("异常信息:{}", ex.getMessage());return Result.error(ex.getMessage());}
}@ExceptionHandler
public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){String message = ex.getMessage();/* if(message.contains("Duplicate entry")){String[] split = message.split(" ");String username = split[2];String msg = username + MessageConstant.ALREADY_EXITS;return Result.error(msg);}else{return Result.error(MessageConstant.UNKNOWN_ERROR);}
*/
//添加一些异常捕获后逻辑处理,将结果返回给前端
}