(Node.js)express制御HTTPステータスコードからエラーへ
17182 ワード
throw new Error('BadRequest')
javascriptでエラーを投げ出すのは簡単で実行しやすい方法です.
expressでもそうです.エラーが投げ出されると、200 OKではなく500個の内部サービスエラーが発生する可能性があります.
エラーオブジェクトに必要なステータスコードを
ErrorにstatusとstatusCodeを入れるのはJavaScriptワールドの標準ではありません.そのため、多くのライブラリのエラークラスにはstatus、statusCodeプロパティがありません.
サンプルライブラリyup/ValidationError
方法は、
expressミドルウェアの使用
エラー処理プログラムでは、
javascriptでエラーを投げ出すのは簡単で実行しやすい方法です.
expressでもそうです.エラーが投げ出されると、200 OKではなく500個の内部サービスエラーが発生する可能性があります.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
throw new Error('BadRequest');
});
app.listen(3000, () => {
console.log('listen');
});
http-errorの使用const express = require('express');
const createError = require('http-errors');
const app = express();
app.get('/', (req, res) => {
throw new createError.BadRequest();
});
app.listen(3000, () => { console.log('listen') });
希望するエラーコードを挿入http-errors
と書くよりも、勒類を直接表現したいのかもしれません.エラーオブジェクトに必要なステータスコードを
status
またはstatusCode
で入れます.const express = require('express');
const app = express();
app.get('/', (req, res) => {
const e = new Error('sample');
e.status = 400;
throw e;
});
app.listen(3000, () => { console.log('listen') });
ライブラリから投げ出されるエラーの制御ErrorにstatusとstatusCodeを入れるのはJavaScriptワールドの標準ではありません.そのため、多くのライブラリのエラークラスにはstatus、statusCodeプロパティがありません.
サンプルライブラリyup/ValidationError
export default function ValidationError(errors, value, field, type) {
this.name = 'ValidationError';
this.value = value;
this.path = field;
this.type = type;
this.errors = [];
this.inner = [];
// ...
this.message =
this.errors.length > 1
? `${this.errors.length} errors occurred`
: this.errors[0];
if (Error.captureStackTrace) Error.captureStackTrace(this, ValidationError);
}
上記のライブラリを使用する場合、エラーが投げ出された場合、どのように対応しますか?方法は、
catch
によってライブラリから投げ出されたエラーをキャプチャし、http-errors
に戻すことです.しかし、既存のコードをすべてcatch
で包むのは無謀だ.expressミドルウェアの使用
エラー処理プログラムでは、
err.name
をチェックし、必要なエラーを投げ出すように処理することができる.const express = require('express');
const createErrors = require('http-errors');
const jwt = require('jsonwebtoken');
const app = express();
app.get('/', (req, res) => {
throw new jwt.JsonWebTokenError('this is sample error');
});
const newErrorMap = new Map([
['JsonWebTokenError', createErrors.BadRequest],
['ValidationError', createErrors.BadRequest],
]);
app.use((err, req, res, next) => {
const newError = newErrorMap.get(err.name);
if (newError) {
next(new newError(err.message));
} else {
next(err);
}
});
app.listen(3000, () => { console.log('listen'); });
Reference
この問題について((Node.js)express制御HTTPステータスコードからエラーへ), 我々は、より多くの情報をここで見つけました https://velog.io/@yunsungyang-omc/Node.js-express에서-에러로-HTTP-status-code-통제하기テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol