typescript 使用react-query处理自定义异常消息

4bbkushb  于 2023-01-21  发布在  TypeScript
关注(0)|答案(2)|浏览(176)

下面是用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)

}

这是我的useMutation函数

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

如何控制台记录抛出的异常的自定义消息?

console.log(error.message)提供了:"Request failed with status code 409"当我想要的消息,我标记的箭头上的图像

xam8gpfp

xam8gpfp1#

onError: (error as AxiosError) => {
        const response = JSON.parse(error.request.response);
        console.log(response.message);
    }
omqzjyyz

omqzjyyz2#

@Chad S.答案有效,但不要将错误像这样放在括号中:error as AxiosError,但将方法返回的错误类型更改为:

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

改为:

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

相关问题