[backend] use common error types
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Copyright 2020 Spotify AB
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/*
|
||||
* A set of common business logic errors.
|
||||
*
|
||||
* The error handler middleware understands these and will translate them to
|
||||
* well formed HTTP responses.
|
||||
*
|
||||
* While these are intentionally analogous to HTTP errors, they are not
|
||||
* intended to be thrown by the request handling layer. In those places, please
|
||||
* use e.g. the http-errors library.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The request is malformed and cannot be processed.
|
||||
*/
|
||||
export class BadRequestError extends Error {
|
||||
readonly cause?: Error;
|
||||
|
||||
constructor(message?: string, cause?: Error) {
|
||||
super(message);
|
||||
Object.setPrototypeOf(this, BadRequestError.prototype);
|
||||
Error.captureStackTrace(this, BadRequestError);
|
||||
this.name = this.constructor.name;
|
||||
this.cause = cause;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The request requires authentication, which was not properly supplied.
|
||||
*/
|
||||
export class UnauthenticatedError extends Error {
|
||||
readonly cause?: Error;
|
||||
|
||||
constructor(message?: string, cause?: Error) {
|
||||
super(message);
|
||||
Object.setPrototypeOf(this, UnauthenticatedError.prototype);
|
||||
Error.captureStackTrace(this, UnauthenticatedError);
|
||||
this.name = this.constructor.name;
|
||||
this.cause = cause;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The authenticated caller is not permitted to perform this request.
|
||||
*/
|
||||
export class ForbiddenError extends Error {
|
||||
readonly cause?: Error;
|
||||
|
||||
constructor(message?: string, cause?: Error) {
|
||||
super(message);
|
||||
Object.setPrototypeOf(this, ForbiddenError.prototype);
|
||||
Error.captureStackTrace(this, ForbiddenError);
|
||||
this.name = this.constructor.name;
|
||||
this.cause = cause;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The requested resource could not be found.
|
||||
*
|
||||
* Note that this error usually is used to indicate that an entity with a given
|
||||
* ID does not exist, rather than signalling that an entire route is missing.
|
||||
*/
|
||||
export class NotFoundError extends Error {
|
||||
readonly cause?: Error;
|
||||
|
||||
constructor(message?: string, cause?: Error) {
|
||||
super(message);
|
||||
Object.setPrototypeOf(this, NotFoundError.prototype);
|
||||
Error.captureStackTrace(this, NotFoundError);
|
||||
this.name = this.constructor.name;
|
||||
this.cause = cause;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The request could not complete due to a conflict in the current state of the
|
||||
* resource.
|
||||
*/
|
||||
export class ConflictError extends Error {
|
||||
readonly cause?: Error;
|
||||
|
||||
constructor(message?: string, cause?: Error) {
|
||||
super(message);
|
||||
Object.setPrototypeOf(this, ConflictError.prototype);
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, ConflictError);
|
||||
}
|
||||
this.name = this.constructor.name;
|
||||
this.cause = cause;
|
||||
}
|
||||
}
|
||||
@@ -14,5 +14,6 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export * from './errors';
|
||||
export * from './logging';
|
||||
export * from './middleware';
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
import express from 'express';
|
||||
import createError from 'http-errors';
|
||||
import request from 'supertest';
|
||||
import * as errors from '../errors';
|
||||
import { errorHandler } from './errorHandler';
|
||||
|
||||
describe('errorHandler', () => {
|
||||
@@ -33,7 +34,7 @@ describe('errorHandler', () => {
|
||||
expect(response.text).toBe('some message');
|
||||
});
|
||||
|
||||
it('takes code from StatusCodeError', async () => {
|
||||
it('takes code from http-errors library errors', async () => {
|
||||
const app = express();
|
||||
app.use('/breaks', () => {
|
||||
throw createError(432, 'Some Message');
|
||||
@@ -45,4 +46,31 @@ describe('errorHandler', () => {
|
||||
expect(response.status).toBe(432);
|
||||
expect(response.text).toContain('Some Message');
|
||||
});
|
||||
|
||||
it('handles well-known error classes', async () => {
|
||||
const app = express();
|
||||
app.use('/BadRequestError', () => {
|
||||
throw new errors.BadRequestError();
|
||||
});
|
||||
app.use('/UnauthenticatedError', () => {
|
||||
throw new errors.UnauthenticatedError();
|
||||
});
|
||||
app.use('/ForbiddenError', () => {
|
||||
throw new errors.ForbiddenError();
|
||||
});
|
||||
app.use('/NotFoundError', () => {
|
||||
throw new errors.NotFoundError();
|
||||
});
|
||||
app.use('/ConflictError', () => {
|
||||
throw new errors.ConflictError();
|
||||
});
|
||||
app.use(errorHandler());
|
||||
|
||||
const r = request(app);
|
||||
expect((await r.get('/BadRequestError')).status).toBe(400);
|
||||
expect((await r.get('/UnauthenticatedError')).status).toBe(401);
|
||||
expect((await r.get('/ForbiddenError')).status).toBe(403);
|
||||
expect((await r.get('/NotFoundError')).status).toBe(404);
|
||||
expect((await r.get('/ConflictError')).status).toBe(409);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,12 +15,12 @@
|
||||
*/
|
||||
|
||||
import { ErrorRequestHandler, NextFunction, Request, Response } from 'express';
|
||||
import * as errors from '../errors';
|
||||
|
||||
/**
|
||||
* Express middleware to handle errors during request processing.
|
||||
*
|
||||
* This is commonly the second to last middleware in the chain (before the
|
||||
* notFoundHandler).
|
||||
* This is commonly the very last middleware in the chain.
|
||||
*
|
||||
* Its primary purpose is not to do translation of business logic exceptions,
|
||||
* but rather to be a gobal catch-all for uncaught "fatal" errors that are
|
||||
@@ -36,8 +36,12 @@ export function errorHandler(): ErrorRequestHandler {
|
||||
error: Error,
|
||||
_request: Request,
|
||||
response: Response,
|
||||
_next: NextFunction,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
if (response.headersSent) {
|
||||
next(error);
|
||||
}
|
||||
|
||||
const status = getStatusCode(error);
|
||||
const message = error.message;
|
||||
response.status(status).send(message);
|
||||
@@ -45,8 +49,8 @@ export function errorHandler(): ErrorRequestHandler {
|
||||
}
|
||||
|
||||
function getStatusCode(error: Error): number {
|
||||
// Look for common http library status codes
|
||||
const knownStatusCodeFields = ['statusCode', 'status'];
|
||||
|
||||
for (const field of knownStatusCodeFields) {
|
||||
const statusCode = (error as any)[field];
|
||||
if (
|
||||
@@ -59,5 +63,22 @@ function getStatusCode(error: Error): number {
|
||||
}
|
||||
}
|
||||
|
||||
// Handle well-known error types
|
||||
switch (error.name) {
|
||||
case errors.BadRequestError.name:
|
||||
return 400;
|
||||
case errors.UnauthenticatedError.name:
|
||||
return 401;
|
||||
case errors.ForbiddenError.name:
|
||||
return 403;
|
||||
case errors.NotFoundError.name:
|
||||
return 404;
|
||||
case errors.ConflictError.name:
|
||||
return 409;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Fall back to internal server error
|
||||
return 500;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user