Spring Boot异常处理最佳实践

标签 spring spring-boot

我有一个关于异常处理的简单问题。 我目前有一个分为多个层的应用程序: Controller 、服务、存储库,我的问题如下:异常处理应该由 Controller 还是服务来完成?

例子:

Controller :

@PostMapping(value = "/{id}/parents", produces = "application/json; charset=utf-8")
public ResponseEntity<AccommodationRequestDTO> resident(@PathVariable Long id, @Valid @RequestBody ParentsAndUrgencyContactDTO parentsAndUrgencyContactDTO) {
    AccommodationRequestDTO saved;
    try {
        saved = this.service.parents(id, parentsAndUrgencyContactDTO);
    } catch (Exception e) {
        throw new ResponseStatusException(
                HttpStatus.INTERNAL_SERVER_ERROR,
                "Failed to save request", e);
    }
    return ResponseEntity.ok(saved);
}

服务:

public AccommodationRequestDTO parents(Long id, ParentsAndUrgencyContactDTO parentsAndUrgencyContactDTO) {
    Optional<AccommodationRequest> accommodationRequest = repository.findById(id);

    if (accommodationRequest.isPresent()) {
        AccommodationRequest saved = accommodationRequest.get();
        Parent firstParent = parentMapper.toEntity(parentsAndUrgencyContactDTO.getFirstParent());
        Parent secondParent = parentMapper.toEntity(parentsAndUrgencyContactDTO.getSecondParent());

        firstParent = parentRepository.save(firstParent);
        secondParent = parentRepository.save(secondParent);

        saved.setFirstParent(firstParent);
        saved.setSecondParent(secondParent);
        saved = this.repository.save(saved);

        return mapper.toDTO(saved);
    } else {
        throw new ResponseStatusException(
                HttpStatus.NOT_FOUND, " with id " + id + " not found !");
    }

}

什么是最佳实践,我应该从 Controller 中删除我的 try-catch 并将其放入我的服务中吗?因为使用此代码,我的 404 异常被 Controller 捕获覆盖。

最佳答案

如果你想抛出异常,在服务层抛出。

最好再定义一个名为exception的包。

并在其中包含您的自定义异常、异常响应和异常处理程序。

我的代码结构如下:

package com.***.demo.exception;

public class DataNotFound extends EntityNotFoundException {
    public DataNotFound(String message) {
        super(message);
    }
}
package com.***.demo.exception;

@Data
@AllArgsConstructor
public class ErrorDetails {
    private Date timestamp;
    private String message;
    private String details;
}
package com.***.demo.exception;

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(DataNotFound.class)
    public ResponseEntity<?> dataNotFoundExceptionHandling(Exception exception, WebRequest request) {
        return new ResponseEntity<>(new ErrorDetails(new Date(), exception.getMessage(), request.getDescription(false)), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> globalExceptionHandling(Exception exception, WebRequest request) {
        return new ResponseEntity<>(new ErrorDetails(new Date(), exception.getMessage(), request.getDescription(false)), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

希望你得到了答案。

关于Spring Boot异常处理最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66762006/

相关文章:

java - 如何使用 Spring 为 bean 的列表属性做贡献?

apache - 如何使用Docker容器在前端和后端之间进行REST调用

java - 使用 JWT 配置 swagger

java - 无法连接到 spring cloud consul(无法设置主机/端口)

java - @Transactional 和 Spring Data

java - 切换大小写或不同的 URL?我应该在 Springboot Controller 中使用什么来调用不同的服务

java - Hibernate 使用分离对象状态覆盖数据库修改

spring - 注销后删除access_token

jsp中的Spring MVC模型访问失败

spring - weblogic.webservice.core.soap.MessageFactoryImpl 无法转换为 javax.xml.soap.MessageFactory