全局异常处理类
全局异常处理是编程中的一个良好的时间,其目的就在于提高程序的稳定性、可靠性以及用户的体验感
全局异常处理类的需要两个关键的注解
@RestControllerAdvice 标志这个类是全局异常处理类 所有异常都会抛到这里
@ExceptionHandler 指定可以捕获哪种类型的异常进行处理 可以自定义异常
案例:
实际解决方案
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局异常处理类
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(BizIllegalException.class) //自定义异常 业务异常
public ResponseEntity<String> exceptionHandler(BizIllegalException e){
log.error("controller call error",e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
@ResponseBody
@ExceptionHandler(value = DuplicateKeyException.class)
public ResponseEntity<String> exceptionHandler(DuplicateKeyException e){
log.error("controller call error",e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("已存在此名称的对象");
}
@ResponseBody
@ExceptionHandler(Exception.class)
public ResponseEntity<String> exceptionHandler(Exception e){
log.error("error",e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误");
}
}
方案写的比较简单可以根据自己的需求进行添加和修改
自定义异常
/**
* 逻辑异常
*/
public class BizIllegalException extends RuntimeException{
public BizIllegalException (String errorMsg){
super(errorMsg);
}
}