feat: typed http signals (Unauthorized, Redirect, NotModified, NotFound)
This commit is contained in:
2 files changed
+50
No files matched your search
@@ -0,0 +1,26 @@
|
||||
export class HttpError extends Error {
|
||||
constructor(readonly status: number, message?: string, readonly body?: unknown) {
|
||||
super(message ?? `HTTP ${status}`);
|
||||
this.name = new.target.name;
|
||||
}
|
||||
}
|
||||
|
||||
export class Unauthorized extends HttpError {
|
||||
constructor(message?: string) { super(401, message); }
|
||||
}
|
||||
|
||||
export class NotFound extends HttpError {
|
||||
constructor(message?: string) { super(404, message); }
|
||||
}
|
||||
|
||||
export class NotModified extends HttpError {
|
||||
constructor() { super(304); }
|
||||
}
|
||||
|
||||
export class Redirect extends HttpError {
|
||||
constructor(readonly location: string) { super(302); }
|
||||
}
|
||||
|
||||
export function isHttpError(e: unknown): e is HttpError {
|
||||
return e instanceof HttpError;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { HttpError, Unauthorized, Redirect, NotModified, NotFound, isHttpError } from '../src/signals';
|
||||
|
||||
test('Unauthorized carries status 401', () => {
|
||||
const e = new Unauthorized('no token');
|
||||
expect(e.status).toBe(401);
|
||||
expect(e.message).toBe('no token');
|
||||
expect(isHttpError(e)).toBe(true);
|
||||
});
|
||||
|
||||
test('Redirect carries location and status 302', () => {
|
||||
const e = new Redirect('/login');
|
||||
expect(e.status).toBe(302);
|
||||
expect(e.location).toBe('/login');
|
||||
});
|
||||
|
||||
test('NotModified is 304, NotFound is 404', () => {
|
||||
expect(new NotModified().status).toBe(304);
|
||||
expect(new NotFound().status).toBe(404);
|
||||
});
|
||||
|
||||
test('isHttpError rejects plain errors', () => {
|
||||
expect(isHttpError(new Error('x'))).toBe(false);
|
||||
});
|
||||
Reference in new issue
Block a user