我正在使用 React 和 Express 创建一个 Web 应用程序。
但是,使用 ky 库对请求的响应将包含默认消息。
如何获取自定义消息?
顺便说一句,这适用于 Postman 和 axios 库。
//Custom Error
class HttpException extends Error {
status: number;
message: string;
constructor(status: number, message: string) {
super(message);
this.status = status;
this.message = message;
}
}
export default HttpException;
//Express
import HttpException from '../exceptions/HttpException';
if (!Object.keys(result).length) throw new HttpException(404, "User does not exist")
//Express error handling middleware
export const errorMiddleware = (err: HttpException, req: express.Request, res: express.Response, next: express.NextFunction) =>{
const status = err.status || 500;
const message = err.message || 'Something went wrong';
res
.status(status)
.send({
status,
message,
})
}
//React
import ky from 'ky'
const customKy = ky.create({
prefixUrl: process.env.NEXT_PUBLIC_API_HOST,
credentials: "include",
headers: { 'Content-Type': 'application/json' },
});
try {
const result: any = await customKy.post("path", { json: data }).json()
} catch (err: any) {
console.log(err.response.status)
console.log(err.response.message)
}
//result console
login.tsx:28 404
login.tsx:29 undefined
默认情况下,ky 从response.statusText 返回错误。您需要更改拦截器中的错误消息。
import ky from 'ky'
const baseApi = ky.create({
prefixUrl: process.env.NEXT_PUBLIC_API_HOST,
credentials: "include",
headers: { 'Content-Type': 'application/json' },
});
const errorInterceptor = async (error) => {
const { response } = error;
const contentType = response.headers.get('content-type');
if (contentType?.indexOf('application/json') !== -1) {
error.message = await response.json();
} else {
error.message = await response.text();
}
return error;
};
const api = baseApi.extend({
hooks: {
beforeError: [errorInterceptor],
},
});
然后在React组件中:
import api from 'file_above'
try {
const result: any = await api.post("path", { json: data }).json()
} catch (err: any) {
console.log(err.response.status)
console.log(err.response.message)
}