built-in exception
NestJSはベースとなるHttpExceptionを継承するいくつかのよく使う例外をデフォルトで提供している。
何が用意されていて、ステータスコードがどれでとか調べるのが面倒なのでまとめた。
exception | response body |
---|---|
BadRequestException | { "statusCode": 400, "message": "Bad Request" } |
UnauthorizedException | { "statusCode": 401, "message": "Unauthorized" } |
ForbiddenException | { "statusCode": 403, "message": "Forbidden" } |
NotFoundException | { "statusCode": 404, "message": "Not Found" } |
MethodNotAllowedException | { "statusCode": 405, "message": "Method Not Allowed" } |
NotAcceptableException | { "statusCode": 406, "message": "Not Acceptable" } |
RequestTimeoutException | { "statusCode": 408, "message": "Request Timeout" } |
ConflictException | { "statusCode": 409, "message": "Conflict" } |
GoneException | { "statusCode": 410, "message": "Gone" } |
PreconditionFailedException | { "statusCode": 412, "message": "Precondition Failed" } |
PayloadTooLargeException | { "statusCode": 413, "message": "Payload Too Large" } |
UnsupportedMediaTypeException | { "statusCode": 415, "message": "Unsupported Media Type" } |
ImATeapotException | { "statusCode": 418, "message": "I'm a teapot" } |
MisdirectedException | { "statusCode": 421, "message": "Misdirected" } |
UnprocessableEntityException | { "statusCode": 422, "message": "Unprocessable Entity" } |
InternalServerErrorException | { "statusCode": 500, "message": "Internal Server Error" } |
NotImplementedException | { "statusCode": 501, "message": "Not Implemented" } |
BadGatewayException | { "statusCode": 502, "message": "Bad Gateway" } |
ServiceUnavailableException | { "statusCode": 503, "message": "Service Unavailable" } |
GatewayTimeoutException | { "statusCode": 504, "message": "Gateway Timeout" } |
HttpVersionNotSupportedException | { "statusCode": 505, "message": "HTTP Version Not Supported" |
使い方
引数なし
import { BadGatewayException } from @nestjs/common
throw new BadGatewayException()
{
"statusCode": 502,
"message": "Bad Gateway"
}
message変更
引数に文字列を入れるとmessage
として挿入され、デフォルトのmessage
はerror
として返される
import { BadGatewayException } from @nestjs/common
throw new BadGatewayException("error message!!")
{
"statusCode": 502,
"message": "error message!!",
"error": "Bad Gateway"
}
await-catch
使うとこんな感じ
import { BadGatewayException } from @nestjs/common
async () => {
await test().catch(e => throw new BadGatewayException(e.message)
}