1- use leptos:: { config:: errors:: LeptosConfigError } ;
1+ use axum:: {
2+ http:: StatusCode ,
3+ response:: { IntoResponse , Response } ,
4+ } ;
5+ use leptos:: config:: errors:: LeptosConfigError ;
26use tonic:: Status ;
37use tracing:: error;
48
9+ use crate :: domain:: models:: validation_error:: ErrorResponse ;
10+
511/// This is custom Result type for the application.
612pub type Result < T > = core:: result:: Result < T , Error > ;
713
@@ -13,6 +19,11 @@ pub enum Error {
1319 /// Error when the password encryption has some issue.
1420 Argon2 ( Box < argon2:: password_hash:: Error > ) ,
1521
22+ /// Error when the request is bad.
23+ BadRequest ( ErrorResponse ) ,
24+
25+ /// Error when the request is forbidden.
26+ InvalidArgument ( String ) ,
1627}
1728
1829impl core:: fmt:: Display for Error {
@@ -56,8 +67,25 @@ impl From<jsonwebtoken::errors::Error> for Error {
5667 }
5768}
5869
70+ impl From < std:: io:: Error > for Error {
71+ fn from ( error : std:: io:: Error ) -> Self {
72+ error ! ( "IO error: {error:?}" ) ;
73+ Self :: Generic ( format ! ( "IO error: {error}" ) )
74+ }
75+ }
76+
77+ impl From < serde_json:: Error > for Error {
78+ fn from ( error : serde_json:: Error ) -> Self {
79+ error ! ( "serde_json error: {error:?}" ) ;
80+ Self :: Generic ( format ! ( "serde_json error: {error}" ) )
81+ }
82+ }
83+
5984//
6085
86+
87+ //
88+
6189impl From < Error > for Status {
6290 fn from ( val : Error ) -> Self {
6391 match val {
@@ -69,19 +97,29 @@ impl From<Error> for Status {
6997 // Error::Unauthenticated(error_message) => {
7098 // Self::unauthenticated(error_message)
7199 // },
72- Error :: Argon2 ( boxed_error) => {
73- Self :: internal ( format ! ( "Argon2 error: {boxed_error:?}" ) )
74- } ,
75- _ => Self :: invalid_argument ( "500 Internal server error" )
100+ Error :: Argon2 ( boxed_error) => Self :: internal ( format ! ( "Argon2 error: {boxed_error:?}" ) ) ,
101+ Error :: InvalidArgument ( error_response) => Self :: invalid_argument ( error_response) ,
102+ Error :: BadRequest ( str) => {
103+ let validation_errors = match serde_json:: to_string ( & str) {
104+ Ok ( str) => str,
105+ _ => "validation error 400." . to_string ( ) ,
106+ } ;
107+
108+ Self :: invalid_argument ( validation_errors)
109+ }
110+ _ => Self :: internal ( "500 Internal server error" ) ,
76111 }
77112 }
78113}
79114
115+ impl IntoResponse for ErrorResponse {
116+ fn into_response ( self ) -> Response {
117+ let validation_errors = match serde_json:: to_string ( & self ) {
118+ Ok ( str) => str,
119+ _ => "validation error 400." . to_string ( ) ,
120+ } ;
80121
81- impl From < std:: io:: Error > for Error {
82- fn from ( error : std:: io:: Error ) -> Self {
83- error ! ( "IO error: {error:?}" ) ;
84- Self :: Generic ( format ! ( "IO error: {error}" ) )
122+ ( StatusCode :: BAD_REQUEST , validation_errors) . into_response ( )
85123 }
86124}
87125
0 commit comments