I have been able to successfully use @ExceptionHandler
annonated methodsorg.springframework.web.bind.annotation.ExceptionHandler
in Controller Classes in my Spring projects to handle exceptions thrown by spring @RestController
Working example:
@Validated
@RestController
@RequestMapping(value = UrlsProperties.API_PATH, produces = MediaType.APPLICATION_JSON, consumes = { MediaType.APPLICATION_JSON })
@Api(value = "MyController", description = "MyController processing and forwarding controller")
public class MyController {
private static Logger log = LogManager.getLogger(MyController.class);
...
@JsonFormat
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseMessage handleMissingParams(MissingServletRequestParameterException ex) {
String name = ex.getParameterName();
log.error(name + " parameter is missing");
return new ResponseMessage(400, ex.getMessage());
}
}
I am trying to achieve the same way of exception handling but for a normal bean, [ not a controller ]. Simply adding an @ExceptionHanlder
annotated method did not seem to catch the exceptions thrown by that bean's methods.
My question is how to handle exceptions thrown by a bean by writing a method inside this bean?
long
, but throws an exception instead, how would you "handle" that in you exceptoin handler? – M. Prokhorov@Component
or@Service
class. Classes by themselves do not return values, they have several methods each might return something. And in my case, several methods might throw the same kind of exception inside thisbean
class. If it was a@Controller
bean, it works, otherwise, no. – aboudirawasafterthrowing
is not an exception handler. It's an action that runs when exception is being thrown, but it doesn't allow any recovery, like a proper exception handler might. – M. Prokhorov