Skip to content

Commit

Permalink
feat (#30): Add Standard Error Handling for undefined Routes
Browse files Browse the repository at this point in the history
  • Loading branch information
lau1944 committed Oct 28, 2023
1 parent 6fc92ae commit 99e2edf
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "bunrest",
"version": "1.3.5",
"version": "1.3.6",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"description": "An express-like API for bun http server",
Expand Down
4 changes: 3 additions & 1 deletion src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,9 @@ class BunServer implements RequestMethod {

// fix (issue 4: unhandle route did not throw an error)
if (!handlers || handlers.length === 0) {
throw new Error(`Cannot ${req.method} ${req.path}`);
console.error(`Cannot ${req.method} ${req.path}`);
res.status(404).send(`${req.method} ${req.path} with a 404`)
return res.getResponse()
}

// fix (issue 13) : How to make it work with async functions or Promises?
Expand Down
33 changes: 33 additions & 0 deletions test/no_handler_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import server from '../src';
import { describe, it, expect, beforeAll, afterAll } from "bun:test";
import router from './router.test';

const app = server();

app.get('/test', (req, res) => {
res.status(200).send('GET /');
});

//add error handler
app.use((req, res, next, err) => {
res.status(500).send('Err /err');
});

const BASE_URL = 'http://localhost:3000';

describe('no handler test', () => {
it('GET', async () => {
const server = app.listen(3000, () => {
console.log('App is listening on port 3000');
});
try {
const res = await fetch(BASE_URL);
expect(res.status).toBe(404);
expect(await res.text()).toBe('GET / with a 404')
} catch (e) {
throw e;
} finally {
server.stop();
}
});
})

0 comments on commit 99e2edf

Please sign in to comment.