Skip to content
Advertisement

what type your response entity should be to have different types of response

I am writing a spring boot application and in my controller some of my APIs need to return different types. for example when everything is ok, I want to return a list of object and in some cases I want to return error messages.

for example I have an API like this:

@PostMapping("/transactions")
public ResponseEntity<Transaction> createTransaction(@RequestBody Transaction transaction) {
    try {

        User user = userRepository.findByUsername_(transaction.getUser().getUsername());
 
        Transaction _transaction = transactionRepository
                .save(new Transaction(transaction.getTransactionID(),user));

        return new ResponseEntity<>(_transaction, HttpStatus.CREATED);
    } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

and I want to generate error messages to return, I also want my API to return the list of object, how we could handle such a thing?

Advertisement

Answer

The best way to achieve what you want is by using the exception handling provided by Spring.

You can have your API declaring what it will return. In your case is a Transaction. If you wanted a list of those items you had just to do List<Transaction> as a return type.

As for error handling, you can use @ControllerAdvice from spring to handle responses when there are exceptions.

@ControllerAdvice
public class ErrorHandler {

    @ExceptionHandler(ApplicationException.class)
    public ResponseEntity handleApplicationException(ApplicationException e) {
        return ResponseEntity.status(e.getCustomError().getCode()).body(e.getCustomError());
    }
}

Best declare your own Application exceptions

@Getter
@Setter
public class ApplicationException extends RuntimeException  {

    private CustomError customError;

    public ApplicationException(CustomError customError){
        super();
        this.customError = customError;
    }
}

And then your error message as an object to be delivered as JSON response

@Getter
@Setter
@NoArgsConstructor
public class CustomError {

    private int code;
    private String message;
    private String cause;

    public CustomError(int code, String message, String cause) {
        this.code = code;
        this.message = message;
        this.cause = cause;
    }

    @Override
    public String toString() {
        return "CustomError{" +
                "code=" + code +
                ", message='" + message + ''' +
                ", cause='" + cause + ''' +
                '}';
    }
}

Then inside your controller method you can just do

@PostMapping("/transactions")
public ResponseEntity<Transaction> createTransaction(@RequestBody Transaction transaction) {
    try {

        User user = userRepository.findByUsername_(transaction.getUser().getUsername());
 
        Transaction _transaction = transactionRepository
                .save(new Transaction(transaction.getTransactionID(),user));

        return new ResponseEntity<>(_transaction, HttpStatus.CREATED);
    } catch (Exception e) {
        throw new ApplicationException( new CustomError(400, "Bad Request",
                        "Transaction is not allowed"));
    }
}

or any other custom message and error that you want

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement