Click here to Skip to main content
16,022,296 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I have an API:

Java
@PutMapping("/{id}")
    public ResponseEntity putAccount(@PathVariable Integer id,
                                        @RequestBody AccountRequest accountRequest)
{
    AccountDto result=accountService.updateAccount(id, accountRequest);
    if (result!=null)
        return ResponseEntity.ok(result);
    else
        return ResponseEntity.ok("No such account in the DB");
}

And the implementation of the service:

public AccountDto updateAccount(Integer id, AccountRequest accountRequest)
{
    Account oldAccount = accountRepository.findById(id).orElse(null);
    if (oldAccount!=null)
    {
    UpdateNonNullFieldsUtil.updateNonNullFields(oldAccount,accountRequest);
        return AccountMapper.INSTANCE.toDto(accountRepository.save(oldAccount));
    }
    return null;
}

How do I handle errors, and do you have any suggestions for improvement if I use it in a real project?

What I have tried:

I tried private final String MESSAGE = "..." for the API response but I wonder if this is good enough for a real project.
Posted
Updated 4-Oct-24 20:58pm
v2

1 solution

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.

Java
//In your controller class...
@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());
    }
}

//In your service class...
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));
}
 
Share this answer
 
Comments
Hung Le Nguyen 6-Oct-24 23:27pm    
If I use Spring security and test (with Postman) the API with no id or no request body, It will return
403 instead of BAD_REQUEST IllegalArgumentException("Account ID cannot be null");
How do I fix it?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900