在 Spring 引导中处理异常的正确方法



我正在阅读 Spring 文档,发现从ResponseEntityExceptionHandler创建子类是处理异常的好方法。但是,我尝试以不同的方式处理异常,因为我需要将BusinessExceptionsTechnicalExceptions区分开来。

创建了一个名为BusinessFault的 bean,它封装了异常详细信息:

业务故障.java

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(value = Include.NON_NULL)
public class BusinessFault {
@JsonProperty(value = "category")
private final String CATEGORY = "Business Failure";
protected String type;
protected String code;
protected String reason;
protected String description;
protected String instruction;
public BusinessFault(String type, String code, String reason) {
this.type = type;
this.code = code;
this.reason = reason;
}
public BusinessFault(String type, String code, String reason, String description, String instruction) {
this.type = type;
this.code = code;
this.reason = reason;
this.description = description;
this.instruction = instruction;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getInstruction() {
return instruction;
}
public void setInstruction(String instruction) {
this.instruction = instruction;
}
public String getCATEGORY() {
return CATEGORY;
}
}

创建了一个BusinessException类,该类通过其构造函数传递的详细信息创建一个BusinessFaultbean 来完成这项工作:

业务例外.java

import com.rest.restwebservices.exception.fault.BusinessFault;
public abstract class BusinessException extends RuntimeException {
private BusinessFault businessFault;
public BusinessException(String type, String code, String reason) {
this.businessFault = new BusinessFault(type, code, reason);
}
public BusinessException(String type, String code, String reason, String description, String instruction) {
this.businessFault = new BusinessFault(type, code, reason, description, instruction);
}
public BusinessException(BusinessFault businessFault) {
this.businessFault = businessFault;
}
public BusinessFault getBusinessFault() {
return businessFault;
}
public void setBusinessFault(BusinessFault businessFault) {
this.businessFault = businessFault;
}
}

创建了一个特定的UserNotFoundException类,该类从BusinessException类扩展而来:

UserNotFoundException.java

import com.rest.restwebservices.exception.fault.BusinessFault;
import com.rest.restwebservices.exception.map.ExceptionMap;
public class UserNotFoundException extends BusinessException {
public UserNotFoundException(BusinessFault businessFault) {
super(businessFault);
}
public UserNotFoundException(String reason) {
super(ExceptionMap.USERNOTFOUND.getType(), ExceptionMap.USERNOTFOUND.getCode(), reason);
}
public UserNotFoundException(String reason, String description, String instruction) {
super(ExceptionMap.USERNOTFOUND.getType(), ExceptionMap.USERNOTFOUND.getCode(), reason, description,
instruction);
}
}

创建了一个BusinessExceptionHandler,但它不是ResponseEntityExceptionHandler的子类,它只有一个@ControllerAdvice注释和一个处理所有抛出BusinessExceptions的方法:

业务异常处理程序.java

import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rest.restwebservices.controller.UserController;
import com.rest.restwebservices.exception.BusinessException;
import com.rest.restwebservices.exception.fault.BusinessFault;
@ControllerAdvice(basePackageClasses = UserController.class)
public class BusinessExceptionHandler {
@ExceptionHandler(BusinessException.class)
@ResponseBody
public ResponseEntity<BusinessFault> genericHandler(HttpServletRequest request, BusinessException ex) {
return new ResponseEntity<BusinessFault>(ex.getBusinessFault(), HttpStatus.OK);
}
}

服务层可以抛出UserNotFoundException

@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User findById(Long id) {
User user = userRepository.findOne(id);
if (user == null)
throw new UserNotFoundException("The ID " + id + " doesn't behave to any user!");
return user;
}
}

它工作正常。但我想知道这是否是处理异常的不良做法?

我对你的异常处理有一点问题。原则上,捕获runtime exceptions,处理它们并将它们发送到客户端是绝对可以的,客户端可能是使用您的 REST 服务并将错误响应作为 JSON 对象获取的人。如果你设法告诉他他做错了什么以及他能做些什么,那就太好了!当然,它会增加一些复杂性,但使用该 API 可能既简单又舒适。

但是,也要考虑使用您的代码的后端开发人员。特别是用户服务中的public User findById(Long id)方法晦涩难懂。这样做的原因是你做了你的BusinessException,特别是未选中UserNotFoundException

如果我加入了您的(后端(团队,并且我将使用该服务编写一些业务逻辑,我会非常确定我必须从该方法中获得什么:我传递一个用户 ID,如果找到它,则返回一个User对象,如果没有,则返回null。这就是为什么我会写这样的代码

User user = userService.findById("42A");
if (user == null) {
// create a User or return an error or null or whatever
} else {
// proceed
}

但是,我永远不会知道,第一个条件永远不会成立,因为您永远不会返回null。我应该如何知道我必须捕获异常?

编译器是否告诉我要捕获它?不,因为它没有被选中。

我会查看您的源代码吗?见鬼,不!您的情况非常简单。该UserNotFoundException可以在一百行代码中另一个类的另一个方法中引发。有时我无法查看它的内部,无论如何,因为该UserService只是依赖项中的编译类。

我读过JavaDoc吗?哈哈哈。比方说,50%的时间我不会,另外50%的时间你忘了记录它,无论如何。

因此,开发人员必须等到他的代码被使用(由客户端或在单元测试中(才能看到它没有按预期工作,迫使他重新设计到目前为止编写的代码。如果你的整个 API 都是这样设计的,那么未经检查的异常就会突然出现,这可能会非常非常烦人,它会花费时间和金钱,而且实际上很容易避免。

我使用类似的方法来处理异常。但就我而言,根据错误状态管理不同的处理程序(例如,用户存在,由于某些不满足的条件而无法注册用户等(。

对于某些特殊情况,您还可以添加通用业务例外。希望它能帮助你感觉更好。

import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rest.restwebservices.controller.UserController;
import com.rest.restwebservices.exception.ResourceNotFoundException;
import com.rest.restwebservices.exception.PreconditionFailedException;
import com.rest.restwebservices.exception.ResourceAlreadyExistsException;
import com.rest.restwebservices.exception.fault.BusinessFault;
@ControllerAdvice(basePackageClasses = UserController.class)
public class BusinessExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseBody
public ResponseEntity<BusinessFault> genericHandler(HttpServletRequest request, ResourceNotFoundException ex) {
return new ResponseEntity<BusinessFault>(ex.getBusinessFault(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(PreconditionFailedException.class)
@ResponseBody
public ResponseEntity<BusinessFault> genericHandler(HttpServletRequest request, PreconditionFailedExceptionex) {
return new ResponseEntity<BusinessFault>(ex.getBusinessFault(), HttpStatus.PRECONDITION_FAILED);
}
@ExceptionHandler(ResourceAlreadyExistsException.class)
@ResponseBody
public ResponseEntity<BusinessFault> genericHandler(HttpServletRequest request, ResourceAlreadyExistsException) {
return new ResponseEntity<BusinessFault>(ex.getBusinessFault(), HttpStatus.CONFLICT);
}
}

相关内容

  • 没有找到相关文章

最新更新