I want to custom error message in AOP around annotations. I used to use @RestControllerAdvice before but It didn't work in AOP around method. it outputs default error message.
I tried to input message in try ~ catch I know it's weird like //// 1 or //// 2
But I can't get to the point :(
@Around("execution(* com.bono.server.controller..*(..))")
@Transactional
public Object caculatePerformanceTime(ProceedingJoinPoint proceedingJoinPoint) {
Object result = null;
try {
result = proceedingJoinPoint.proceed();
} catch (CustomeException e) { ////// 1
throw new ErrorMessage(CustomError.HTTP_400_MISTYPE);
}
catch (Throwable throwable) { /////// 2
return new ErrorMessage(CustomError.HTTP_400_MISTYPE);
}
return result;
}
@Getter
@Setter
public class ErrorMessage {
private int errorCode;
private String errorMessage;
public ErrorMessage(CustomError customError) {
this.errorCode = customError.errorCode();
this.errorMessage = customError.errorMessage();
}
}
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GroupExceptionAdvice extends ResponseEntityExceptionHandler {
//// 1
@ExceptionHandler(value = CustomeException.class)
public ResponseEntity<CustomErrorResponse> customhandleNotSatisfied(Exception ex, WebRequest request) {
CustomErrorResponse error = new CustomErrorResponse();
error.setTimestamp(LocalDateTime.now());
error.setError(ex.getMessage());
error.setStatus(HttpStatus.NOT_FOUND.value());
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
//// 2
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = CustomException.class)
public ErrorMessage handlerUnResolvedAddressException(MisTypingException e) {
return new ErrorMessage(CustomError.HTTP_400_MISTYPE);
}
}
{
"timestamp": "2019-08-12T01:14:16.467+0000",
"status": 500,
"error": "Internal Server Error",
"message": "class com.bono.server.config.exception.ErrorMessage cannot be cast to class org.springframework.http.ResponseEntity (com.bono.server.config.exception.ErrorMessage and org.springframework.http.ResponseEntity are in unnamed module of loader 'app')",
"path": "/bono/api/alarm"
}
I want to show like this
{
"code" : 102,
"message" : "got it !"
}
Converting my previous comments into an answer because the OP said that they solved his problem.
Your ErrorMessage
class does not extend any Exception
or Throwable
, so how can you throw it? The code should not even compile and yield a compile error like:
No exception of type ErrorMessage can be thrown;
an exception type must be a subclass of Throwable
I.e. in your sample class I you ought to write something like
public class ErrorMessage extends Exception {
// (...)
}
for a checked exception or
public class ErrorMessage extends RuntimeException {
// (...)
}
for a non-checked exception. But your class definition does not extend anything, i.e. implicitly it directly extends Object
.