arsenal11
arsenal11

Reputation: 69

Handling a custom exception

I'm trying to create a custom exception "UserNotFoundException" that will be thrown when a GET request for a user that doesn't exist comes in.

class UserNotFoundException extends Exception {

    public UserNotFoundException(Long id) {
        super(id);
    }
}

I know super(id) won't work, but I have no idea how to deal with this problem. The exception is thrown here:

@GetMapping("/users/{id}")
    User one(@PathVariable Long id) {

        return repository.findById(id)
            .orElseThrow(() -> new UserNotFoundException(id));
    }

Thanks for the help.

Upvotes: 1

Views: 856

Answers (1)

shinjw
shinjw

Reputation: 3421

You are attempting to call a parent constructor that does not exist.

class UserNotFoundException extends Exception {

    public UserNotFoundException(Long id) {
        super(id);
    }

}

The Exception class provides you have the following constructors:

public Exception()
public Exception(String message)
public Exception(String message, Throwable cause)
public Exception(Throwable cause)
protected Exception(String message, Throwable cause,
                    boolean enableSuppression,
                    boolean writableStackTrace)

If you would like to see a message come through with the id you will have to convert your Long to a String.

public UserNotFoundException(Long id) {
    super(String.valueOf(id));
}

You also have the ability to have custom fields for your UserNotFoundException if you intend on leveraging ExceptionHandler

private Long id;
public UserNotFoundException(Long id) {
    super();
    this.id = id;
}

// Getters

Why it fails when converting the message to a string: Checked vs Unchecked Exceptions Keep in mind that Exception is a checked exception which requires you to have explicit handling for -- otherwise, this will fail at compile time.

You may want to look into RuntimeException to set up an unchecked exception.

See the following for more details on RuntimeException vs Exception:

Difference between java.lang.RuntimeException and java.lang.Exception

See the following for a similar question and answers that can point you in the right direction:

How can I write custom Exceptions?

Upvotes: 4

Related Questions