我有一个已经实现的 Controller 方法,它返回一个值或抛出一个异常。
@Override
@PostMapping(Endpoint.SUB_RESOURCE)
@ResponseStatus(HttpStatus.CREATED)
public EmployeeBankAccountOutputDto createBankAccount(@ApiParam("Account data") @RequestBody final EmployeeBankAccountInputDto accountCreationDto) {
try {
return service.createBankAccount(accountCreationDto);
} catch (InvalidAccountDataException ex) {
throw new InvalidAccountDataResponseException(ex, ex.getErrors());}
} catch (CountryNotFoundException ex) {
throw new CountryNotFoundResponseException(ex.getCountryCode(), ex);
}
}
在这段代码中,我只想记录警告级别的异常消息,而不是抛出异常,因为我不想看到类似这样的内容:
14:37:02,610 ERROR [] c.m.w.ApiExceptionHandler:135 - Account API error occurred: 400
所以如果我把
log.warn(ex.getMessage());
到第一个 catch 语句,它给出了
missing return statement
正常情况下该 catch block 的错误。那么如何处理不抛出调用 api 的异常并正确发送异常消息,因为方法的返回类型是 dto?
最佳答案
如果无法创建帐户,您不想返回任何内容。
至少您要返回 400
错误响应以向客户端发出问题信号。
您可以使用 ResponseEntity
作为方法的返回类型来指示响应代码。这也意味着你也必须改变成功案例中返回对象的方式。
如果您不想传输特定的错误消息而只想传输错误代码,则可以通过这种方式更改方法:
public ResponseEntity<EmployeeBankAccountOutputDto> createBankAccount(@ApiParam("Account data") @RequestBody final EmployeeBankAccountInputDto accountCreationDto) {
try {
return ResponseEntity.ok(service.createBankAccount(accountCreationDto));
} catch (InvalidAccountDataException ex) {
log.warn(ex.getMessage());
return ResponseEntity.badRequest();
}
}
如果您还想传输特定的错误消息,您可以使用响应正文:
public ResponseEntity<EmployeeBankAccountOutputDto> createBankAccount(@ApiParam("Account data") @RequestBody final EmployeeBankAccountInputDto accountCreationDto) {
try {
return ResponseEntity.ok(service.createBankAccount(accountCreationDto));
} catch (InvalidAccountDataException ex) {
log.warn(ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
}
}
请注意,如果您需要在多个 Controller 中执行此处理,这可能意味着异常处理程序将是一种更简洁的方法。
例如以统一的方式处理 InvalidAccountDataException
:
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
Logger LOGGER = LoggerFactory.getLogger(MyExceptionHandler.class);
@ExceptionHandler(value = { InvalidAccountDataException.class })
protected ResponseEntity<Object> handleGenericExceptions(InvalidAccountDataException ex, WebRequest request) {
log.warn(ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
}
}
当然,如果需要,您可以添加更多方法来处理更多类型的异常。
关于java - 如何在 Java 中将异常消息返回给调用 api?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54255312/