如何为http状态码发送自定义错误信息与node.js

我正在使用node.js进行用户authentication的基于rest的api。 我想发送一个自定义的错误消息更具描述性,如“不正确的用户名/密码组合”。 在演示文稿方面,我使用fetch和redux-saga来反应原生。

这里是用于将用户名/密码发送到其余层并接收返回的http错误消息的redux-saga代码:

export const login = ({userName, password}) => { return fetch(globals.BASE_URL + `/api/login`, { method : 'POST', headers : { 'Accept' : 'application/json', 'Content-Type' : 'application/json' }, body: JSON.stringify({ userName: userName, password: password }) }); } const fetchLoginStatus = function* (action) { const response = yield call(login, action); try { if (response.status >= 200 && response.status < 300) { const userInfo = yield response.json(); yield put({type: LOGIN_SUCCESS, authToken: userInfo.authToken}); } else { yield put({type: ERROR_MESSAGE_OCCURRED, errorMessage: response.statusText}); } } catch (error) { yield put({type: ERROR_MESSAGE_OCCURRED, errorMessage: error}); } } 

这是用于返回错误消息的node.js代码:

 app.use(function (err: Error, req: express.Request, res: express.Response, next: express.NextFunction) { if (err instanceof IncorrectLoginError) { //Tried this approach initially, did not work either //res.statusMessage = err.message; //res.status(400).end(); res.status(400).json({ error: err.message }); } else { return res.end(); } }); 

下面是这个问题,当我从模拟器运行debugging器,并检查从调用返回的响应对象时,我一直在响应对象中获得以下内容:

 Response { type: 'default', status: 400, ok: false, statusText: undefined, headers: Headers { map: { 'x-frame-options': [Object], 'strict-transport-security': [Object], connection: [Object], 'x-dns-prefetch-control': [Object], date: [Object], 'x-content-type-options': [Object], 'content-length': [Object], 'x-download-options': [Object], vary: [Object], 'x-xss-protection': [Object], 'content-type': [Object] } }, url: 'http://localhost:3000/api/login', _bodyInit: 'Bad Request', _bodyText: 'Bad Request' } 

最终,我想设置statusCode与状态码,但不起作用。 对于第二种方法,我试图传递一个错误string与返回对象,但看着Response对象,这是不工作。 什么是正确的方式来设置statusCode伴随statusCode?

以下是从Web Storm上的“testingREST风格的Web服务”运行时显示的错误消息:

在这里输入图像描述