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 usenew 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
Remove Duplicates from a List of Objects Based on Property in Java 8
How to Fill Hashmap from Java Property File With Spring @Value
How to Identify File Type by Base64 Encoded String of a Image
Java Classes to Generate the Given Json String
Intellij Incorrectly Saying No Beans of Type Found for Autowired Repository
How to Trim White Space from All Elements in Array
Regular Expression for Uppercase Letters in a String
Java Spring: Best Way to Convert a File to a Multipartfile
How to Prevent Duplicate Results in Hibernate
What Happens When Base and Derived Classes Each Have Variables With the Same Name
Java 8 Lambda Create List of Strings from List of Objects
Spring Boot - Exception Encountered During Context Initialization. How to Know the Reason of Error
Wrong Answer in Task - Mistake in Algorithm
Arraylist: How Does the Size Increase
How to Create Unique Column With Jpa
Junit 5 - No Parameterresolver Registered for Parameter
How to Set Default Download Directory in Selenium Chrome Capabilities