feat: add custom errors

This commit is contained in:
Joachim Van Herwegen
2020-05-28 10:57:22 +02:00
parent cc8f965495
commit 57405f3e26
3 changed files with 51 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
/**
* An abstract class for all errors that could be thrown by Solid.
* All errors inheriting from this should fix the status code thereby hiding the HTTP internals from other components.
*/
export abstract class HttpError extends Error {
public statusCode: number;
/**
* Creates a new HTTP error. Subclasses should call this with their fixed status code.
* @param statusCode - HTTP status code needed for the HTTP response.
* @param name - Error name. Useful for logging and stack tracing.
* @param message - Message to be thrown.
*/
protected constructor (statusCode: number, name: string, message: string) {
super(message);
this.statusCode = statusCode;
this.name = name;
}
}

View File

@@ -0,0 +1,15 @@
import { HttpError } from './HttpError';
/**
* An error thrown when incoming data is not supported.
* Probably because an {@link AsyncHandler} returns false on the canHandle call.
*/
export class UnsupportedHttpError extends HttpError {
/**
* Default message is 'The given input is not supported by the server configuration.'.
* @param message - Optional, more specific, message.
*/
public constructor (message?: string) {
super(400, 'UnsupportedHttpError', message || 'The given input is not supported by the server configuration.');
}
}

View File

@@ -0,0 +1,17 @@
import { UnsupportedHttpError } from '../../../../src/util/errors/UnsupportedHttpError';
describe('An UnsupportedHttpError', (): void => {
it('has status code 400.', async (): Promise<void> => {
const error = new UnsupportedHttpError('test');
expect(error.statusCode).toEqual(400);
expect(error.message).toEqual('test');
expect(error.name).toEqual('UnsupportedHttpError');
});
it('has a default message if none was provided.', async (): Promise<void> => {
const error = new UnsupportedHttpError();
expect(error.message).toEqual('The given input is not supported by the server configuration.');
});
});