spring 我应该在Sping Boot 中为空结果返回EntityNotFoundException吗?[已关闭]

xzlaal3s  于 2022-11-28  发布在  Spring
关注(0)|答案(1)|浏览(123)

已关闭。此问题为opinion-based。当前不接受答案。
**想要改进此问题吗?**请更新问题,以便editing this post可以使用事实与引用来回答.

2天前关闭。
Improve this question
在Sping Boot 应用程序中,我使用@RestControllerAdvice创建了一个全局异常处理程序类,如下所示:

@Slf4j(topic = "GLOBAL_EXCEPTION_HANDLER")
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {-

    @Override
    @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers,
                                                                  HttpStatus status,
                                                                  WebRequest request) {
        ErrorResponse errorResponse = new ErrorResponse(HttpStatus.UNPROCESSABLE_ENTITY.value(), VALIDATION_ERROR);
        for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
            errorResponse.addValidationError(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return ResponseEntity.unprocessableEntity().body(errorResponse);
    }

    @ExceptionHandler(EntityNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<Object> handleEntityNotFoundException(EntityNotFoundException ex,
                                                                WebRequest request) {
        log.error(ENTITY_NOT_FOUND, ex);
        return buildErrorResponse(ex, HttpStatus.NOT_FOUND, request);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<Object> handleAllUncaughtException(Exception ex, WebRequest request) {
        log.error(UNKNOWN_ERROR, ex);
        return buildErrorResponse(ex, UNKNOWN_ERROR, HttpStatus.INTERNAL_SERVER_ERROR, request);
    }

    private ResponseEntity<Object> buildErrorResponse(Exception ex,
                                                      HttpStatus httpStatus,
                                                      WebRequest request) {
        return buildErrorResponse(ex, ex.getMessage(), httpStatus, request);
    }

    private ResponseEntity<Object> buildErrorResponse(Exception ex,
                                                      String message,
                                                      HttpStatus httpStatus,
                                                      WebRequest request) {
        ErrorResponse errorResponse = new ErrorResponse(httpStatus.value(), message);
        if (printStackTrace && isTraceOn(request)) {
            errorResponse.setStackTrace(ExceptionUtils.getStackTrace(ex));
        }
        return ResponseEntity.status(httpStatus).body(errorResponse);
    }

    @Override
    public ResponseEntity<Object> handleExceptionInternal(
            Exception ex,
            Object body,
            HttpHeaders headers,
            HttpStatus status,
            WebRequest request) {
        return buildErrorResponse(ex, status, request);
    }
}

我的服务方法如下所示:

private List<Employee> findByName(String name) {
    List<Employee> employees = employeeRepo.findByName(name);
 
    // At this stage, should I check if the result is empty list and then throw exception?
    if (employees.isEmpty()) {
        throw new EntityNotFoundException("Not found any employee");
    }

    return employees;
}

在返回员工列表之前,是否应该检查结果是否为空列表,然后抛出异常?

bxgwgixi

bxgwgixi1#

这取决于具体情况和您希望实现的目标。这是一种向请求客户端显示没有员工使用所请求的名称的方式。您应该将“runways.isEmpty()”替换为“employees.isEmpty()”,否则可能会在构建过程中出错。
由于您已经在使用自定义的ExceptionHandler,因此可以轻松地抛出Exception,然后使用您自己的自定义异常消息中断异常消息。
另一个不抛出异常的选项是,您可以只返回空列表,如果您有一个FE应用程序,您可以检查列表是否为空,并相应地向客户端显示相应的消息。

相关问题