提问人:yuval t 提问时间:9/19/2023 更新时间:9/19/2023 访问量:22
使用中间件传递错误不起作用 socket.io 但它在通用服务器中确实有效
passing error with socket.io middleware doesnt work but it does work in the general server
问:
在我的服务器中,我得到了我的 Custon 错误处理程序,每次我通过他(使用 next(error))时,他都会接受错误,但是当我使用 socket.io 并尝试向他传递错误时,它不起作用,我不知道为什么,你能解决吗?
io.use((socket, next) => {
const authorizationHeader = socket.handshake.headers?.authorization;
if (!authorizationHeader) {
next(new CustomError(401, NOT_AUTHORIZED_MESSAGE));
return;
}
const token = authorizationHeader.split(' ')[1];
const isVerfied = !!decodeLoginCookieToken(token);
if (isVerfied) {
next();
} else {
next(new CustomError(401, NOT_AUTHORIZED_MESSAGE));
}
});
答: 暂无答案
评论
class CustomError extends Error { status: number; message: string; constructor(status: number = 500, message: string = 'internal server error') { super(message); this.status = status; this.message = message; } } export default CustomError;
export const errorHandler = ( error: CustomError, request: Request, response: Response, next: NextFunction ) => { const status = error.status ?? 500; const message = error.message ?? 'Internal server error'; return response.status(status).json({ message, }); }; export default errorHandler;