Validation Errors. What’s the best approach?

Do you throw an exception? Do you return an object like ‘{ data: {}, errors: [] }’? How would you best handle this? It’s also a requirement that all the validation takes place to return a list of the items that are invalid. Any resources on this concept would be much appreciated too!
1 Reply
LemonMantis
LemonMantis13mo ago
Depends on how the approach is aligned with your application: throw exception can be useful when you want to ensure that invalid data does not proceed further and potentially cause issues down the line. returning an object: This allows you to provide more context and information about the validation errors while still allowing the caller to handle the response appropriately. I personally like to return an object to provide more context to the client as it makes easier to handle it, for your case this could be a easy approach. however an application that throws exceptions tends to be more robust.
"An application that uses exceptions is more robust than an application that uses return codes. An application that uses exceptions can also give the cleanest code, since return codes don't have to be checked after every call."
"An application that uses exceptions is more robust than an application that uses return codes. An application that uses exceptions can also give the cleanest code, since return codes don't have to be checked after every call."
https://www.ibm.com/support/pages/which-better-return-code-or-exception#:~:text=An%20application%20that%20uses%20exceptions,be%20checked%20after%20every%20call. hope it helps and if i didnt understand ur question properly let me know