I am working at a exception handler and a custom exception class
@ControllerAdvice
public class GeneralExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GeneralExceptionHandler.class);
@ExceptionHandler(ApiException.class)
public static ResponseEntity<Object> handleExceptions(ApiException e) {
logger.info("Exception handled:" e.getMessage() " with http status: " e.getHttpStatus());
return new ResponseEntity<>(e.getMessage(), e.getHttpStatus());
}
}
And
public class ApiException extends Exception{
private final String message;
private final HttpStatus httpStatus;
public ApiException(String message, HttpStatus httpStatus) {
this.message = message;
this.httpStatus = httpStatus;
}
@Override
public String getMessage() {
return message;
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
}
When i throw an ApiException in my service class, it should be catched in controller layer but it doesn't work. These are my service and controller functions.
@Override
public Boolean deleteSubjectType(int subjectTypeId) throws ApiException {
SubjectType subjectType=subjectTypeRepository.findById(subjectTypeId)
.orElseThrow(()->new ApiException("Subject Type Id not found", HttpStatus.NOT_FOUND));
return true;
}
And
@DeleteMapping("/{subjectTypeId}")
public ResponseEntity<Object> deleteSubjectType(@PathVariable int subjectTypeId) {
subjectTypeService.deleteSubjectType(subjectTypeId);
return ResponseEntity.ok().body(null);
}
CodePudding user response:
Based on the code provided, I found that it works fine. Make sure that spring can scan the folder where the GeneralExceptionHandler resides
CodePudding user response:
@RestControllerAdvice
public class GeneralExceptionHandler {
private static final Logger logger =
LoggerFactory.getLogger(GeneralExceptionHandler.class);
@ExceptionHandler(Exception.class)
public static ResponseEntity<Object> handleExceptions(Exception e) {
logger.info("Exception handled:" e.getMessage() " with http
status: " e.getHttpStatus());
return new ResponseEntity<>(e.getMessage(), e.getHttpStatus());
}
}
Also add following code to your application.properties
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false