How to Return Different Types of Responseentity in Spring MVC or Spring-Boot

return different type of response from controller when there is an error state

You can use ResponseEntity<?> to return either Customer or ErrorResponse like this.

@PostMapping("/generate/send")
fun handleRequest( @RequestHeader header1: String,
@RequestHeader header2: String): ResponseEntity<?> {
// ...
}

Spring MVC: How to return different type in ResponseEntity body

There are two problems here:-

  • Your return type has to be changed to match the two response subclasses ResponseEntity<? extends AbstractResponse>

  • When you instantiate your ResponseEntity you cannot use the simplified <> syntax you have to specify which response class you are going to use new ResponseEntity<ErrorResponse> (errResponse, HTTPStatus.BAD_REQUEST);

     @ResponseBody ResponseEntity<? extends AbstractResponse> createUser(@RequestBody String requestBody) {
    if(!valid(requestBody) {
    ErrorResponse errResponse = new ErrorResponse();
    //populate with error information
    return new ResponseEntity<ErrorResponse> (errResponse, HTTPStatus.BAD_REQUEST);
    }
    createUser();
    CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse();
    // populate with more info
    return new ResponseEntity<CreateUserSuccessResponse> (successResponse, HTTPStatus.OK);
    }

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

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

Correct way to return different objects on a java spring boot api?

as mentioned in the comments by @jlh91, I was satisfied with ResponseEntity<?> on the main method and for each case, its method would return ResponseEntity<String> or ResponseEntity<Integer>

Spring Return error format in ResponseEntity

Try following code. It will send image itself in response on accessing this API.

@GetMapping(value = "/image/{id}")
public ResponseEntity<?> getImageById(@PathParam Long id) throws Exception {
String imageData = this.entityRepository.findById(id).orElse(null).getData();
byte[] imageByte = Base64.getDecoder().decode(new String(imageData).getBytes("UTF-8"));
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
return new ResponseEntity<>(imageByte, headers, HttpStatus.OK);
}


Related Topics



Leave a reply



Submit