统一处理异常思路
1、自定义异常 BusinessException
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
public BusinessException(String message) {
super(message);
}
}
2、统一响应
public class CommonResponse implements Serializable {
private static final long serialVersionUID = 1L;
private String message = "";
public CommonResponse(final String message) {
this.message = message;
}
public CommonResponse() {
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
3、异常统一处理 @ControllerAdvice
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<CommonResponse> handleExcepting(BusinessException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.APPLICATION_JSON)
.body(new CommonResponse(e.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<CommonResponse> handleExcepting(Exception e) {
log.error("error", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON).body(new CommonResponse("服务器内部错误"));
}
}
4、应用Demo
@Authorization
@PostMapping("profile")
public AdminVo getAdminInfo() {
AdminVo adminVo = adminService.getAdminInfo();
if (adminVo == null) {
throw new BusinessException("自定义异常");
}
return adminVo;
}
好处:给前端统一的响应,便于处理
@ControllerAdvice ???