Issue
How do I handle error states inside a controller?
For example: My controller which accepts two headers. If both the headers are null then it's a problem so return response of type ErrorResponse
else if all ok then return response of type customer
.
However, there is a problem as we defined the handler method to return ResponseEntity<Customer>
.
My controller:
@PostMapping("/generate/send")
fun handleRequest( @RequestHeader header1: String,
@RequestHeader header2: String): ResponseEntity<Customer> {
if(header1 == null && header2== null) { // ERROR if both header null
return ResponseEntity(ErrorResponse(""), HttpStatus.BAD_REQUEST )
}
return ResponseEntity(Customer(), HttpStatus.OK )
}
how do refactor my code to prevent this or handle this type of situation where I have to return a different type because of an error?
Solution
You can use ResponseEntity<?>
to return either Customer
or ErrorResponse
like this.
@PostMapping("/generate/send")
fun handleRequest( @RequestHeader header1: String,
@RequestHeader header2: String): ResponseEntity<?> {
// ...
}
Answered By - J.F.
Answer Checked By - Marie Seifert (JavaFixing Admin)