1

Here is my global exception handler written in Spring Boot

data class ErrorResponse(
    val status: Int? = null,
    val message: String? = null
)

@ControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(ItemAlreadyExistsException::class)
    fun handleItemAlreadyExistsException(e: ItemAlreadyExistsException?): ResponseEntity<ErrorResponse> =
        ResponseEntity(ErrorResponse(HttpStatus.CONFLICT.value(), e?.message.toString()), HttpStatus.CONFLICT)

}

And here is my useMutation function

    const useSignUp = useMutation<Employer, Error, Employer>(
        (employer) => signUpAsEmployer(employer),
        {
            onError: (error) => {
                console.log(error.message)
            }
        }
    );

How can I console log the custom message from thrown Exception?

enter image description here

console.log(error.message) gives me: "Request failed with status code 409" while I want the message I marked by arrow on the image

2 Answers 2

2
    onError: (error as AxiosError) => {
        const response = JSON.parse(error.request.response);
        console.log(response.message);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

I get this error: TS2339: Property 'request' does not exist on type 'Error'
Inform typescript that it's an AxiosError not any ol run of the mill Error. I have edited my answer to add the cast.
0

The @Chad S. answer works but do not cast the error inside the parenthises like this: error as AxiosError but change the method returned error type from this:

 const useSignUp = useMutation<Employer, Error, Employer>(
        (employer) => signUpAsEmployer(employer),
        {
            onError: (error) => {
                console.log(error.message)
            }
        }
    );

to this:

 const useSignUp = useMutation<Employer, AxiosError, Employer>(
        (employer) => signUpAsEmployer(employer),
        {
            onError: (error) => {
                console.log(error.message)
            }
        }
    );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.