Skip to content

Commit b740020

Browse files
author
haoxin
committedApr 9, 2017
throw error if file not exists
closes #43
1 parent 92fd0b0 commit b740020

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed
 

‎index.js

+5-2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
const debug = require('debug')('koa-send');
66
const resolvePath = require('resolve-path');
7+
const createError = require('http-errors');
78
const assert = require('assert');
89
const fs = require('mz/fs');
910

@@ -59,7 +60,7 @@ async function send(ctx, path, opts = {}) {
5960
// normalize path
6061
path = decode(path);
6162

62-
if (-1 == path) return ctx.throw('failed to decode', 400);
63+
if (-1 == path) return ctx.throw(400, 'failed to decode');
6364

6465
// index file support
6566
if (index && trailingSlash) path += index;
@@ -109,7 +110,9 @@ async function send(ctx, path, opts = {}) {
109110
}
110111
} catch (err) {
111112
const notfound = ['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'];
112-
if (~notfound.indexOf(err.code)) return;
113+
if (notfound.includes(err.code)) {
114+
throw createError(404, err);
115+
}
113116
err.status = 500;
114117
throw err;
115118
}

‎package.json

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
"license": "MIT",
2323
"dependencies": {
2424
"debug": "^2.6.3",
25+
"http-errors": "^1.6.1",
2526
"mz": "^2.6.0",
2627
"resolve-path": "^1.3.3"
2728
},

‎test/index.js

+20
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,26 @@ describe('send(ctx, file)', function(){
1919
.get('/')
2020
.expect(404, done);
2121
})
22+
23+
it('should throw 404 error', function(done){
24+
const app = new Koa()
25+
26+
let error
27+
app.use(async (ctx) => {
28+
try {
29+
await send(ctx, __dirname + '/fixtures/hello.txt')
30+
} catch (err) {
31+
error = err
32+
}
33+
})
34+
35+
request(app.listen())
36+
.get('/')
37+
.expect(404, () => {
38+
assert.equal(error.status, 404)
39+
done()
40+
})
41+
})
2242
})
2343

2444
describe('when the path is relative', function(){

0 commit comments

Comments
 (0)
Please sign in to comment.