Created
July 25, 2018 09:02
-
-
Save jhm-ciberman/1005aeca2327e66282be89110f64a443 to your computer and use it in GitHub Desktop.
LaravelValidationError.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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