'How can I throw a custom exception along with status code?

So I have a code like this,

public customDTO doSomething() {
  try {
    //calling an API here storing result to customDTO
    if (customDTO.a == customDTO.b)
    // return 500 to controller that is calling doSomething() and go to catch
  } catch (CustomException e) {
    // update status of customDTO
  }
  
}

I am new to Java and Spring so still trying to figure out how to tackle this. Would really appreciate if someone could help me out here.



Solution 1:[1]

Instead of returning CustomDto object from the method, return ResponseEntity where you can modify the status code as you please. Like following

public CustomDTO doSomething() {
    try {
        //calling an API here storing result to customDTO
        if (customDTO.a == customDTO.b) {
            // Here you're sending 500, instead of that you can send any staus you want
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return ResponseEntity.ok().build(customDto.a); // if everything is ok
            
    } catch (CustomException e) {
            // update status of customDTO
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Subham