balderdashy / waterline-docs

WARNING: The content in this repo is out of date! See https://github.com/balderdashy/sails-docs for the most up-to-date documentation
452 stars 163 forks source link

How should I throw an error that will trigger a "not found" or "invalid request" response in a waterline adapter? #84

Open shaunc opened 9 years ago

shaunc commented 9 years ago

I am writing an adapter; in one case creating an object requires that id of parent object is passed in. I would like to throw an error that will trigger an appropriate error response in sails (not 500 -- 400 or 404 perhaps).

How do I do this?

dmarcelino commented 9 years ago

Hi @shaunc, I'm not using sails so I'm not the best person to answer this but have you tried using waterline-errors? It's used by a few official adapters.

shaunc commented 9 years ago

@dmarcelino -- thanks for the pointer. The issue I see there are:

1) errors are strings, not Error instances (in case, e.g. you want to include stack trace for debug purposes, set an http code, or use "instanceof" to identify error) 2) no provision for customizing messages ("invalid parameter: 'foo' needs to be a valid 'bar'" or whatever) 3) are consumers supposed to just match the string error message to identify?

I guess at the least, as a documentation issue this issue is still a bug, as the doc doesn't include a reference to waterline-errors. I'd prefer a more robust solution myself.

devinivy commented 9 years ago

A waterline error shouldn't cause any particular HTTP response code. If you're using sails, I suggest creating a res.negotiate response method to deal with transforming errors (i.e. from waterline) into reasonable HTTP responses based upon your particular requirements.

The errors in waterline-error actually are Error instances! The errors are created with some getter magic. Here's what it looks like in my console:

> require('waterline-errors').adapter.PrimaryKeyUpdate
{ [AdapterError: Primary key cannot be updated]
  name: 'AdapterError',
  message: 'Primary key cannot be updated' }
> require('waterline-errors').adapter.PrimaryKeyUpdate instanceof Error
true

Edit I do agree, though– this might make for a good piece of info to go in the docs.