【问题标题】:Service and controller layer exception handling design pattern服务和控制器层异常处理设计模式
【发布时间】:2019-02-13 19:28:59
【问题描述】:

所以这是我当前对 rest-api 端点的实现,我想处理一些极端情况,例如找不到用户或公寓,所以我会抛出合适的异常,但是如何显示我在控制器中处理它?现在它并没有真正起作用,如果我设置一个不存在的 id,它会像往常一样工作,并且我没有收到相应的错误消息。

服务层:

public void delete(Long flatId) {
        flatRepository.findById(flatId).ifPresentOrElse(flat -> {
                    List<User> residents = flat.getResidents();
                    residents.forEach(resident -> resident.setFlat(null));
                    flatRepository.delete(flat);
                },
                () -> new ResourceNotFoundException("Flat " + flatId + " found"));

}

控制器层:

@DeleteMapping("/flats/{flatId}")
    public void deleteFlat(@PathVariable Long flatId) {
        flatService.delete(flatId);
}

全局异常处理程序:

@ControllerAdvice
@RestController
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public final ErrorDetails handleResourceNotFoundException(ResourceNotFoundException ex) {
        return new ErrorDetails(LocalDateTime.now(), ex.getMessage(), 404);
    }

    @ExceptionHandler(ResourceAlreadyDefinedException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    public final ErrorDetails handleResourceAlreadyDefinedException(ResourceAlreadyDefinedException ex) {
        return new ErrorDetails(LocalDateTime.now(),  ex.getMessage(), 409);
    }

}

更新:我创建了这个全局异常处理程序,但是如果我向我的 api 发送一个不存在 id 的删除请求,它不会向我发送 404,它只会回复 200。如果我有一个返回值,例如在这种情况下,它按预期工作。

        public Flat get(Long id) {
                return flatRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Flat " + id + " not found"));
        }


     @GetMapping("/flats/{flatId}")
        public ResponseEntity<Flat> getFlat(@PathVariable Long flatId) {
            return ResponseEntity.ok(flatService.get(flatId));
     }

【问题讨论】:

标签: spring rest spring-boot controller layer


【解决方案1】:

您可以使用@ControllerAdvice@ExceptionHandler 为所有控制器和特定类型的异常实现全局异常处理。

查看here 的示例。

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 2010-10-01
    • 2014-09-24
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2020-09-22
    相关资源
    最近更新 更多