Skip to content

Instantly share code, notes, and snippets.

@jhm-ciberman
Created July 25, 2018 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhm-ciberman/1005aeca2327e66282be89110f64a443 to your computer and use it in GitHub Desktop.
Save jhm-ciberman/1005aeca2327e66282be89110f64a443 to your computer and use it in GitHub Desktop.
LaravelValidationError.ts
/**
This is a typical Laravel API JSON validation error.
{
"message": "The given data was invalid.",
"errors": {
"name": [
"The name field is required."
],
"email": [
"The email field is required."
]
}
}
And this is the interface in Typescript for this error. And a small helper class.
*/
export interface LaravelValidationError {
message: string,
errors: {
[field: string]: string[]
}
}
export default class ValidationError extends Error {
private _data: LaravelValidationError;
constructor(data: LaravelValidationError) {
super(data.message);
this._data = data;
}
public static isValidationError(error: any): error is LaravelValidationError {
return (error.message && error.errors);
}
public getHTML() {
let str = `<p>${this._data.message}</p>`;
str += "<ul>";
for (const field of Object.keys(this._data.errors)) {
for (const errorString of this._data.errors[field]) {
str += `<li>${errorString}</li>`;
}
}
str += "</ul>";
return str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment