mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-01-16 07:32:11 +01:00
Refactor error payload logic
This commit is contained in:
14
src/index.ts
14
src/index.ts
@ -3,6 +3,7 @@
|
||||
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrismaD1 } from '@prisma/adapter-d1';
|
||||
import { formatError } from './utils/error';
|
||||
|
||||
export interface Env {
|
||||
DB: D1Database;
|
||||
@ -209,17 +210,7 @@ export default {
|
||||
|
||||
} catch (error) {
|
||||
console.error('Worker error:', error);
|
||||
const payload: Record<string, unknown> = {
|
||||
error: 'Internal Server Error',
|
||||
message: error instanceof Error ? error.message : 'Unknown error'
|
||||
};
|
||||
if (
|
||||
typeof process !== 'undefined' &&
|
||||
process.env?.NODE_ENV !== 'production'
|
||||
) {
|
||||
payload.stack = error instanceof Error ? error.stack : undefined;
|
||||
}
|
||||
return new Response(JSON.stringify(payload), {
|
||||
return new Response(JSON.stringify(formatError(error)), {
|
||||
status: 500,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@ -229,3 +220,4 @@ export default {
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
13
src/utils/error.ts
Normal file
13
src/utils/error.ts
Normal file
@ -0,0 +1,13 @@
|
||||
export function formatError(error: unknown): Record<string, unknown> {
|
||||
const payload: Record<string, unknown> = {
|
||||
error: 'Internal Server Error',
|
||||
message: error instanceof Error ? error.message : 'Unknown error'
|
||||
};
|
||||
if (
|
||||
typeof process !== 'undefined' &&
|
||||
process.env?.NODE_ENV !== 'production'
|
||||
) {
|
||||
payload.stack = error instanceof Error ? error.stack : undefined;
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
23
tests/formatError.test.ts
Normal file
23
tests/formatError.test.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert';
|
||||
import { formatError } from '../src/utils/error';
|
||||
|
||||
const originalEnv = process.env.NODE_ENV;
|
||||
|
||||
test('includes stack when not in production', () => {
|
||||
delete process.env.NODE_ENV;
|
||||
const err = new Error('boom');
|
||||
const payload = formatError(err);
|
||||
assert.ok('stack' in payload);
|
||||
});
|
||||
|
||||
test('omits stack in production', () => {
|
||||
process.env.NODE_ENV = 'production';
|
||||
const err = new Error('boom');
|
||||
const payload = formatError(err);
|
||||
assert.ok(!('stack' in payload));
|
||||
});
|
||||
|
||||
test.after(() => {
|
||||
if (originalEnv === undefined) delete process.env.NODE_ENV; else process.env.NODE_ENV = originalEnv;
|
||||
});
|
||||
Reference in New Issue
Block a user