Taking the code below into consideration:
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Resource
private MessageSource messageSource;
private HttpHeaders headers(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
private ResponseError responseError(String message,HttpStatus statusCode){
ResponseError responseError = new ResponseError();
responseError.setStatus("error");
responseError.setError(message);
responseError.setStatusCode(statusCode.value());
return responseError;
}
@ExceptionHandler(Exception.class)
private ResponseEntity<Object> handleGeneral(Exception e, WebRequest request) {
if (e.getClass().isAssignableFrom(UndeclaredThrowableException.class)) {
UndeclaredThrowableException exception = (UndeclaredThrowableException) e;
return handleBusinessException((BusinessException) exception.getUndeclaredThrowable(), request);
} else {
String message = messageSource.getMessage("error.server", new Object[]{e.getMessage()}, null);
ResponseError error = responseError(message,HttpStatus.INTERNAL_SERVER_ERROR);
return handleExceptionInternal(e, error, headers(), HttpStatus.INTERNAL_SERVER_ERROR, request);
}
}
@ExceptionHandler({BusinessException.class})
private ResponseEntity<Object> handleBusinessException(BusinessException e, WebRequest request) {
ResponseError error = responseError(e.getMessage(),HttpStatus.CONFLICT);
return handleExceptionInternal(e, error, headers(), HttpStatus.CONFLICT, request);
}
}
What would be the biggest difference between replacing
if (e.getClass().isAssignableFrom(UndeclaredThrowableException.class)) {
with
if (e instanceof UndeclaredThrowableException) {
Line 19.
I found some explanations but none detailed enough.I wanted to understand the situations in which I should use isAssignableFrom or instanceof.
Vitor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
e.getClass().isAssignableFrom(Whatever.class)
tests whether the runtime class of e
is a superclass of Whatever
,
e instanceof Whatever
tests whether the runtime class of e
is a subclass of Whatever
.
In your code, the latter makes more sense, but in modern Java, there is an even shorter and clearer way of writing that:
if (e instanceof Whatever w) {
// w is now a variable of type Whatever
}
- isAssignableFrom: This method checks if the class represented by one Class object is the same as, or is a superclass or superinterface of, the class represented by another Class object. It is used to determine if one class is assignable from another class or interface.
- instanceof: This operator checks if an object is an instance of a particular class or interface, including instances of subclasses. It is used to test if an object is of a particular type.