Skip to content

Commit

Permalink
Add NotFoundError to common/errors & use it in modules/siteselect
Browse files Browse the repository at this point in the history
  • Loading branch information
eemeli committed Sep 13, 2018
1 parent 94894ba commit 430258e
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
4 changes: 3 additions & 1 deletion common/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,15 @@ server start.
## Errors

```js
const { AuthError, InputError } = require('@kansa/common/errors')
const { AuthError, InputError, NotFoundError } = require('@kansa/common/errors')
```

### `new AuthError(message: string)`

### `new InputError(message: string)`

### `new NotFoundError(message: string)`

Handled by the server's error handling. May also have their `status` set.

## Log entries
Expand Down
10 changes: 9 additions & 1 deletion common/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,12 @@ function InputError(message = 'Input error') {
}
InputError.prototype = new Error()

module.exports = { AuthError, InputError }
function NotFoundError(message = 'Not Found') {
this.name = 'NotFoundError'
this.message = message
this.status = 404
this.stack = new Error().stack
}
NotFoundError.prototype = new Error()

module.exports = { AuthError, InputError, NotFoundError }
10 changes: 5 additions & 5 deletions modules/siteselect/lib/admin.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { InputError } = require('@kansa/common/errors')
const { InputError, NotFoundError } = require('@kansa/common/errors')
const { parseToken } = require('./token')

class Admin {
Expand All @@ -13,19 +13,19 @@ class Admin {

findToken(req, res, next) {
const token = parseToken(req.params.token)
if (!token) return res.status(404).json({ error: 'not found' })
if (!token) return next(new NotFoundError())
this.db
.oneOrNone(`SELECT * FROM token_lookup WHERE token=$1`, token)
.then(data => {
if (data) res.json(data)
else res.status(404).json({ error: 'not found' })
if (!data) throw new NotFoundError()
res.json(data)
})
.catch(next)
}

findVoterTokens(req, res, next) {
const { id } = req.params
if (!id) return res.status(404).json({ error: 'not found' })
if (!id) return next(new NotFoundError())
this.db
.any(
`
Expand Down

0 comments on commit 430258e

Please sign in to comment.