Your first step would be to learn more about error trapping and how to handle it, as a basic explanation see -
Java Exceptions - Try...Catch[
^]
You can now modify both your controller and service methods using the following code -
In your controller you need to return different
HTTP status codes[
^] codes based on your situation, the basic ones will be -
200 OK for successful updates...
404 Not Found when the account doesn't exist...
400 Bad Request for invalid input...
500 Internal Server Error for unexpected exceptions...
In your service method I have added null checks for both the id and 'accountRequest' parameters.
Instead of returning null when the account is not found, you can now throw an 'IllegalArgumentException'.
I have removed the null check and else block, as it will now throw an exception if the account is not found.
@PutMapping("/{id}")
public ResponseEntity<?> putAccount(@PathVariable Integer id,
@RequestBody AccountRequest accountRequest) {
try {
AccountDto result = accountService.updateAccount(id, accountRequest);
if (result != null) {
return ResponseEntity.ok(result);
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("No such account found with ID: " + id);
}
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Invalid input: " + e.getMessage());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred while updating the account: " + e.getMessage());
}
}
public AccountDto updateAccount(Integer id, AccountRequest accountRequest) {
if (id == null) {
throw new IllegalArgumentException("Account ID cannot be null");
}
if (accountRequest == null) {
throw new IllegalArgumentException("Account request cannot be null");
}
Account oldAccount = accountRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("No account found with ID: " + id));
UpdateNonNullFieldsUtil.updateNonNullFields(oldAccount, accountRequest);
return AccountMapper.INSTANCE.toDto(accountRepository.save(oldAccount));
}