Search code examples
javaspring-boothibernateresth2

Error handling class is not being triggered correctly and problem with h2 database on Spring Boot application while creating REST API


I have been working on a simple project to create a REST API. There is a two problem on the project. Such as:

  1. data.sql: The sql query that I have written was perfectly working on other project. But on this project it creates table but not inserted data on the table. When go I to H2 console and run the query it works fine. As I said, It works fine if I create new project and run the query table created and inserted without any problem.

  2. DogNotFoundException.java: This class is used to handle error. If an id is requested that doesn’t exist, appropriately handle the error. But when I run the application and enter the wrong id the message doesn't appear. If no error was handled manually by default it gives Whitelabel Error Page and this is what happens if I enter wrong id.

Link of the Project


Solution

  • The first one is a duplicate of this issue

    To Summarize,

    • You have to separate the create(on schema.sql) and insert(data.sql) scripts
    • Add the below property on application.properties, this ensures the schema.sql is picked up and the create scripts are executed spring.jpa.hibernate.ddl-auto=none

    On the second one,

    @ResponseStatus is not a replacement for @ExceptionHandler. Basically, you use the former if you have a straightforward implementation of just passing the HTTP status code (404 in this case). If you need a dynamic message that needs to be sent, then you can use the below implementation

    @ExceptionHandler(value= DogNotFoundException.class)
    public ResponseEntity<String> returnNotFoundException(DogNotFoundException ex){
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
    

    and on service class return the message you wish to DogNotFoundException

    optionalBreed.orElseThrow(() -> new DogNotFoundException("Breed not found"));
    

    Hope this helps