logo
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
//! Some common error types.

use std::{
    convert::Infallible,
    error::Error as StdError,
    fmt::{self, Debug, Display, Formatter},
    string::FromUtf8Error,
};

use headers::{ContentRange, HeaderMapExt};
use http::Method;

use crate::{http::StatusCode, IntoResponse, Response};

macro_rules! define_http_error {
    ($($(#[$docs:meta])* ($name:ident, $status:ident);)*) => {
        $(
        $(#[$docs])*
        #[allow(non_snake_case)]
        #[inline]
        pub fn $name(err: impl StdError + Send + Sync + 'static) -> Error {
            Error::new(err, StatusCode::$status)
        }
        )*
    };
}

/// Represents a type that can be converted to [`Error`].
pub trait ResponseError {
    /// The status code of this error.
    fn status(&self) -> StatusCode;

    /// Convert this error to a HTTP response.
    fn as_response(&self) -> Response
    where
        Self: StdError + Send + Sync + 'static,
    {
        Response::builder()
            .status(self.status())
            .body(self.to_string())
    }
}

enum ErrorSource {
    BoxedError(Box<dyn StdError + Send + Sync>),
    #[cfg(feature = "anyhow")]
    Anyhow(anyhow::Error),
    #[cfg(feature = "eyre06")]
    Eyre06(eyre06::Report),
}

impl Debug for ErrorSource {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ErrorSource::BoxedError(err) => Debug::fmt(err, f),
            #[cfg(feature = "anyhow")]
            ErrorSource::Anyhow(err) => Debug::fmt(err, f),
            #[cfg(feature = "eyre06")]
            ErrorSource::Eyre06(err) => Debug::fmt(err, f),
        }
    }
}

type BoxAsResponseFn = Box<dyn Fn(&Error) -> Response + Send + Sync + 'static>;

enum AsResponse {
    Status(StatusCode),
    Fn(BoxAsResponseFn),
}

impl AsResponse {
    #[inline]
    fn from_status(status: StatusCode) -> Self {
        AsResponse::Status(status)
    }

    fn from_type<T: ResponseError + StdError + Send + Sync + 'static>() -> Self {
        AsResponse::Fn(Box::new(|err| {
            let err = err.downcast_ref::<T>().expect("valid error");
            err.as_response()
        }))
    }

    fn as_response(&self, err: &Error) -> Response {
        match self {
            AsResponse::Status(status) => Response::builder().status(*status).body(err.to_string()),
            AsResponse::Fn(f) => f(err),
        }
    }
}

/// General response error.
///
/// # Create from any error types
///
/// ```
/// use poem::{error::InternalServerError, handler, Result};
///
/// #[handler]
/// async fn index() -> Result<String> {
///     Ok(std::fs::read_to_string("example.txt").map_err(InternalServerError)?)
/// }
/// ```
///
/// # Create you own error type
///
/// ```
/// use poem::{error::ResponseError, handler, http::StatusCode, Endpoint, Request, Result};
///
/// #[derive(Debug, thiserror::Error)]
/// #[error("my error")]
/// struct MyError;
///
/// impl ResponseError for MyError {
///     fn status(&self) -> StatusCode {
///         StatusCode::BAD_GATEWAY
///     }
/// }
///
/// fn do_something() -> Result<(), MyError> {
///     Err(MyError)
/// }
///
/// #[handler]
/// async fn index() -> Result<()> {
///     Ok(do_something()?)
/// }
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let resp = index.get_response(Request::default()).await;
/// assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
/// assert_eq!(resp.into_body().into_string().await.unwrap(), "my error");
/// # });
/// ```
///
/// # Custom error response
///
/// ```
/// use poem::{error::ResponseError, handler, http::StatusCode, Response, Result, Request, Body, Endpoint};
///
/// #[derive(Debug, thiserror::Error)]
/// #[error("my error")]
/// struct MyError;
///
/// impl ResponseError for MyError {
///     fn status(&self) -> StatusCode {
///         StatusCode::BAD_GATEWAY
///     }
///
///     fn as_response(&self) -> Response {
///         let body = Body::from_json(serde_json::json!({
///             "code": 1000,
///             "message": self.to_string(),
///         })).unwrap();
///         Response::builder().status(self.status()).body(body)
///     }
/// }
///
/// fn do_something() -> Result<(), MyError> {
///     Err(MyError)
/// }
///
/// #[handler]
/// async fn index() -> Result<()> {
///     Ok(do_something()?)
/// }
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let resp = index.get_response(Request::default()).await;
/// assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
/// assert_eq!(resp.into_body().into_json::<serde_json::Value>().await.unwrap(),
/// serde_json::json!({
///     "code": 1000,
///     "message": "my error",
/// }));
/// # });
/// ```
///
/// # Downcast the error to concrete error type
/// ```
/// use poem::{error::NotFoundError, Error};
///
/// let err: Error = NotFoundError.into();
///
/// assert!(err.is::<NotFoundError>());
/// assert_eq!(err.downcast_ref::<NotFoundError>(), Some(&NotFoundError));
/// ```
pub struct Error {
    as_response: AsResponse,
    source: ErrorSource,
}

impl Debug for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Error")
            .field("source", &self.source)
            .finish()
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match &self.source {
            ErrorSource::BoxedError(err) => Display::fmt(err, f),
            #[cfg(feature = "anyhow")]
            ErrorSource::Anyhow(err) => Display::fmt(err, f),
            #[cfg(feature = "eyre06")]
            ErrorSource::Eyre06(err) => Display::fmt(err, f),
        }
    }
}

impl From<Infallible> for Error {
    fn from(_: Infallible) -> Self {
        unreachable!()
    }
}

impl<T: ResponseError + StdError + Send + Sync + 'static> From<T> for Error {
    fn from(err: T) -> Self {
        Error {
            as_response: AsResponse::from_type::<T>(),
            source: ErrorSource::BoxedError(Box::new(err)),
        }
    }
}

impl From<Box<dyn StdError + Send + Sync>> for Error {
    fn from(err: Box<dyn StdError + Send + Sync>) -> Self {
        (StatusCode::INTERNAL_SERVER_ERROR, err).into()
    }
}

impl From<(StatusCode, Box<dyn StdError + Send + Sync>)> for Error {
    fn from((status, err): (StatusCode, Box<dyn StdError + Send + Sync>)) -> Self {
        Error {
            as_response: AsResponse::from_status(status),
            source: ErrorSource::BoxedError(err),
        }
    }
}

#[cfg(feature = "anyhow")]
impl From<anyhow::Error> for Error {
    fn from(err: anyhow::Error) -> Self {
        Error {
            as_response: AsResponse::from_status(StatusCode::INTERNAL_SERVER_ERROR),
            source: ErrorSource::Anyhow(err),
        }
    }
}

#[cfg(feature = "eyre06")]
impl From<eyre06::Error> for Error {
    fn from(err: eyre06::Error) -> Self {
        Error {
            as_response: AsResponse::from_status(StatusCode::INTERNAL_SERVER_ERROR),
            source: ErrorSource::Eyre06(err),
        }
    }
}

#[cfg(feature = "anyhow")]
impl From<(StatusCode, anyhow::Error)> for Error {
    fn from((status, err): (StatusCode, anyhow::Error)) -> Self {
        Error {
            as_response: AsResponse::from_status(status),
            source: ErrorSource::Anyhow(err),
        }
    }
}

#[cfg(feature = "eyre06")]
impl From<(StatusCode, eyre06::Report)> for Error {
    fn from((status, err): (StatusCode, eyre06::Report)) -> Self {
        Error {
            as_response: AsResponse::from_status(status),
            source: ErrorSource::Eyre06(err),
        }
    }
}

impl From<StatusCode> for Error {
    fn from(status: StatusCode) -> Self {
        Error::from_status(status)
    }
}

impl Error {
    /// Create a new error object from any error type with `503
    /// INTERNAL_SERVER_ERROR` status code.
    #[inline]
    pub fn new<T: StdError + Send + Sync + 'static>(err: T, status: StatusCode) -> Self {
        Self {
            as_response: AsResponse::from_status(status),
            source: ErrorSource::BoxedError(Box::new(err)),
        }
    }

    /// create a new error object from status code.
    pub fn from_status(status: StatusCode) -> Self {
        #[derive(Debug, thiserror::Error)]
        #[error("{0}")]
        struct StatusError(StatusCode);

        impl ResponseError for StatusError {
            fn status(&self) -> StatusCode {
                self.0
            }
        }

        StatusError(status).into()
    }

    /// Create a new error object from string with `503 INTERNAL_SERVER_ERROR`
    /// status code.
    pub fn from_string(msg: impl Into<String>, status: StatusCode) -> Self {
        #[derive(Debug, thiserror::Error)]
        #[error("{0}")]
        struct StringError(String);

        Self::new(StringError(msg.into()), status)
    }

    /// Downcast this error object by reference.
    #[inline]
    pub fn downcast_ref<T: StdError + Send + Sync + 'static>(&self) -> Option<&T> {
        match &self.source {
            ErrorSource::BoxedError(err) => err.downcast_ref::<T>(),
            #[cfg(feature = "anyhow")]
            ErrorSource::Anyhow(err) => err.downcast_ref::<T>(),
            #[cfg(feature = "eyre06")]
            ErrorSource::Eyre06(err) => err.downcast_ref::<T>(),
        }
    }

    /// Attempts to downcast the error to a concrete error type.
    #[inline]
    pub fn downcast<T: StdError + Send + Sync + 'static>(self) -> Result<T, Error> {
        let as_response = self.as_response;

        match self.source {
            ErrorSource::BoxedError(err) => match err.downcast::<T>() {
                Ok(err) => Ok(*err),
                Err(err) => Err(Error {
                    as_response,
                    source: ErrorSource::BoxedError(err),
                }),
            },
            #[cfg(feature = "anyhow")]
            ErrorSource::Anyhow(err) => match err.downcast::<T>() {
                Ok(err) => Ok(err),
                Err(err) => Err(Error {
                    as_response,
                    source: ErrorSource::Anyhow(err),
                }),
            },
            #[cfg(feature = "eyre06")]
            ErrorSource::Eyre06(err) => match err.downcast::<T>() {
                Ok(err) => Ok(err),
                Err(err) => Err(Error {
                    as_response,
                    source: ErrorSource::Eyre06(err),
                }),
            },
        }
    }

    /// Returns `true` if the error type is the same as `T`.
    #[inline]
    pub fn is<T: StdError + Debug + Send + Sync + 'static>(&self) -> bool {
        match &self.source {
            ErrorSource::BoxedError(err) => err.is::<T>(),
            #[cfg(feature = "anyhow")]
            ErrorSource::Anyhow(err) => err.is::<T>(),
            #[cfg(feature = "eyre06")]
            ErrorSource::Eyre06(err) => err.is::<T>(),
        }
    }

    /// Consumes this to return a response object.
    pub fn as_response(&self) -> Response {
        self.as_response.as_response(self)
    }
}

define_http_error!(
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::BAD_REQUEST`].
    (BadRequest, BAD_REQUEST);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::UNAUTHORIZED`].
    (Unauthorized, UNAUTHORIZED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::PAYMENT_REQUIRED`].
    (PaymentRequired, PAYMENT_REQUIRED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::FORBIDDEN`].
    (Forbidden, FORBIDDEN);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::NOT_FOUND`].
    (NotFound, NOT_FOUND);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::METHOD_NOT_ALLOWED`].
    (MethodNotAllowed, METHOD_NOT_ALLOWED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::NOT_ACCEPTABLE`].
    (NotAcceptable, NOT_ACCEPTABLE);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::PROXY_AUTHENTICATION_REQUIRED`].
    (ProxyAuthenticationRequired, PROXY_AUTHENTICATION_REQUIRED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::REQUEST_TIMEOUT`].
    (RequestTimeout, REQUEST_TIMEOUT);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::CONFLICT`].
    (Conflict, CONFLICT);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::GONE`].
    (Gone, GONE);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::LENGTH_REQUIRED`].
    (LengthRequired, LENGTH_REQUIRED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::PAYLOAD_TOO_LARGE`].
    (PayloadTooLarge, PAYLOAD_TOO_LARGE);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::URI_TOO_LONG`].
    (UriTooLong, URI_TOO_LONG);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::UNSUPPORTED_MEDIA_TYPE`].
    (UnsupportedMediaType, UNSUPPORTED_MEDIA_TYPE);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::RANGE_NOT_SATISFIABLE`].
    (RangeNotSatisfiable, RANGE_NOT_SATISFIABLE);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::IM_A_TEAPOT`].
    (ImATeapot, IM_A_TEAPOT);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::MISDIRECTED_REQUEST`].
    (MisdirectedRequest, MISDIRECTED_REQUEST);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::UNPROCESSABLE_ENTITY`].
    (UnprocessableEntity, UNPROCESSABLE_ENTITY);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::LOCKED`].
    (Locked, LOCKED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::FAILED_DEPENDENCY`].
    (FailedDependency, FAILED_DEPENDENCY);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::UPGRADE_REQUIRED`].
    (UpgradeRequired, UPGRADE_REQUIRED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::PRECONDITION_FAILED`].
    (PreconditionFailed, PRECONDITION_FAILED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::PRECONDITION_REQUIRED`].
    (PreconditionRequired, PRECONDITION_REQUIRED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::TOO_MANY_REQUESTS`].
    (TooManyRequests, TOO_MANY_REQUESTS);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE`].
    (RequestHeaderFieldsTooLarge, REQUEST_HEADER_FIELDS_TOO_LARGE);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS`].
    (UnavailableForLegalReasons, UNAVAILABLE_FOR_LEGAL_REASONS);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::EXPECTATION_FAILED`].
    (ExpectationFailed, EXPECTATION_FAILED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::INTERNAL_SERVER_ERROR`].
    (InternalServerError, INTERNAL_SERVER_ERROR);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::NOT_IMPLEMENTED`].
    (NotImplemented, NOT_IMPLEMENTED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::BAD_GATEWAY`].
    (BadGateway, BAD_GATEWAY);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::SERVICE_UNAVAILABLE`].
    (ServiceUnavailable, SERVICE_UNAVAILABLE);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::GATEWAY_TIMEOUT`].
    (GatewayTimeout, GATEWAY_TIMEOUT);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::HTTP_VERSION_NOT_SUPPORTED`].
    (HttpVersionNotSupported, HTTP_VERSION_NOT_SUPPORTED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::VARIANT_ALSO_NEGOTIATES`].
    (VariantAlsoNegotiates, VARIANT_ALSO_NEGOTIATES);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::INSUFFICIENT_STORAGE`].
    (InsufficientStorage, INSUFFICIENT_STORAGE);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::LOOP_DETECTED`].
    (LoopDetected, LOOP_DETECTED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::NOT_EXTENDED`].
    (NotExtended, NOT_EXTENDED);
    /// Wraps any error into [`Error`] and the status code is [`StatusCode::NETWORK_AUTHENTICATION_REQUIRED`].
    (NetworkAuthenticationRequired, NETWORK_AUTHENTICATION_REQUIRED);
);

/// A specialized Result type for Poem.
pub type Result<T, E = Error> = ::std::result::Result<T, E>;

/// Represents a type that can be converted to `poem::Result<T>`.
///
/// # Example
///
/// ```
/// use poem::error::{IntoResult, NotFoundError};
///
/// let res = "abc".into_result();
/// assert!(matches!(res, Ok("abc")));
///
/// let res = Err::<(), _>(NotFoundError).into_result();
/// assert!(res.is_err());
/// let err = res.unwrap_err();
/// assert!(err.is::<NotFoundError>());
/// ```
pub trait IntoResult<T: IntoResponse> {
    /// Consumes this value returns a `poem::Result<T>`.
    fn into_result(self) -> Result<T>;
}

impl<T, E> IntoResult<T> for Result<T, E>
where
    T: IntoResponse,
    E: Into<Error> + Debug + Send + Sync + 'static,
{
    #[inline]
    fn into_result(self) -> Result<T> {
        self.map_err(Into::into)
    }
}

impl<T: IntoResponse> IntoResult<T> for T {
    #[inline]
    fn into_result(self) -> Result<T> {
        Ok(self)
    }
}

macro_rules! define_simple_errors {
    ($($(#[$docs:meta])* ($name:ident, $status:ident, $err_msg:literal);)*) => {
        $(
        $(#[$docs])*
        #[derive(Debug, thiserror::Error, Copy, Clone, Eq, PartialEq)]
        #[error($err_msg)]
        pub struct $name;

        impl ResponseError for $name {
            fn status(&self) -> StatusCode {
                StatusCode::$status
            }
        }
        )*
    };
}

define_simple_errors!(
    /// Only the endpoints under the router can get the path parameters, otherwise this error will occur.
    (ParsePathError, BAD_REQUEST, "invalid path params");

    /// Error occurred in the router.
    (NotFoundError, NOT_FOUND, "not found");

    /// Error occurred in the router.
    (MethodNotAllowedError, METHOD_NOT_ALLOWED, "method not allowed");

    /// Error occurred in the `Cors` middleware.
    (CorsError, UNAUTHORIZED, "unauthorized");
);

/// A possible error value when reading the body.
#[derive(Debug, thiserror::Error)]
pub enum ReadBodyError {
    /// Body has been taken by other extractors.
    #[error("the body has been taken")]
    BodyHasBeenTaken,

    /// Body is not a valid utf8 string.
    #[error("parse utf8: {0}")]
    Utf8(#[from] FromUtf8Error),

    /// Payload too large
    #[error("payload too large")]
    PayloadTooLarge,

    /// Io error.
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
}

impl ResponseError for ReadBodyError {
    fn status(&self) -> StatusCode {
        match self {
            ReadBodyError::BodyHasBeenTaken => StatusCode::INTERNAL_SERVER_ERROR,
            ReadBodyError::Utf8(_) => StatusCode::BAD_REQUEST,
            ReadBodyError::Io(_) => StatusCode::BAD_REQUEST,
            ReadBodyError::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
        }
    }
}

/// A possible error value when parsing cookie.
#[cfg(feature = "cookie")]
#[cfg_attr(docsrs, doc(cfg(feature = "cookie")))]
#[derive(Debug, thiserror::Error)]
pub enum ParseCookieError {
    /// Cookie value is illegal.
    #[error("cookie is illegal")]
    CookieIllegal,

    /// A `Cookie` header is required.
    #[error("`Cookie` header is required")]
    CookieHeaderRequired,

    /// Cookie value is illegal.
    #[error("cookie is illegal: {0}")]
    ParseJsonValue(#[from] serde_json::Error),
}

#[cfg(feature = "cookie")]
impl ResponseError for ParseCookieError {
    fn status(&self) -> StatusCode {
        StatusCode::BAD_REQUEST
    }
}

/// A possible error value when extracts data from request fails.
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
#[error("data of type `{0}` was not found.")]
pub struct GetDataError(pub &'static str);

impl ResponseError for GetDataError {
    fn status(&self) -> StatusCode {
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

/// A possible error value when parsing form.
#[derive(Debug, thiserror::Error)]
pub enum ParseFormError {
    /// Invalid content type.
    #[error("invalid content type `{0}`, expect: `application/x-www-form-urlencoded`")]
    InvalidContentType(String),

    /// `Content-Type` header is required.
    #[error("expect content type `application/x-www-form-urlencoded`")]
    ContentTypeRequired,

    /// Url decode error.
    #[error("url decode: {0}")]
    UrlDecode(#[from] serde_urlencoded::de::Error),
}

impl ResponseError for ParseFormError {
    fn status(&self) -> StatusCode {
        match self {
            ParseFormError::InvalidContentType(_) => StatusCode::UNSUPPORTED_MEDIA_TYPE,
            ParseFormError::ContentTypeRequired => StatusCode::UNSUPPORTED_MEDIA_TYPE,
            ParseFormError::UrlDecode(_) => StatusCode::BAD_REQUEST,
        }
    }
}

/// A possible error value when parsing JSON.
#[derive(Debug, thiserror::Error)]
#[error("parse: {0}")]
pub struct ParseJsonError(#[from] pub serde_json::Error);

impl ResponseError for ParseJsonError {
    fn status(&self) -> StatusCode {
        StatusCode::BAD_REQUEST
    }
}

/// A possible error value when parsing query.
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct ParseQueryError(#[from] pub serde_urlencoded::de::Error);

impl ResponseError for ParseQueryError {
    fn status(&self) -> StatusCode {
        StatusCode::BAD_REQUEST
    }
}

/// A possible error value when parsing multipart.
#[cfg(feature = "multipart")]
#[cfg_attr(docsrs, doc(cfg(feature = "multipart")))]
#[derive(Debug, thiserror::Error)]
pub enum ParseMultipartError {
    /// Invalid content type.
    #[error("invalid content type `{0}`, expect: `multipart/form-data`")]
    InvalidContentType(String),

    /// `Content-Type` header is required.
    #[error("expect content type `multipart/form-data`")]
    ContentTypeRequired,

    /// Parse error.
    #[error("parse: {0}")]
    Multipart(#[from] multer::Error),

    /// Body is not a valid utf8 string.
    #[error("parse utf8: {0}")]
    Utf8(#[from] FromUtf8Error),

    /// Io error
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
}

#[cfg(feature = "multipart")]
impl ResponseError for ParseMultipartError {
    fn status(&self) -> StatusCode {
        match self {
            ParseMultipartError::InvalidContentType(_) => StatusCode::UNSUPPORTED_MEDIA_TYPE,
            ParseMultipartError::ContentTypeRequired => StatusCode::UNSUPPORTED_MEDIA_TYPE,
            ParseMultipartError::Multipart(_) => StatusCode::BAD_REQUEST,
            ParseMultipartError::Utf8(_) => StatusCode::BAD_REQUEST,
            ParseMultipartError::Io(_) => StatusCode::BAD_REQUEST,
        }
    }
}

/// A possible error value when parsing typed headers.
#[derive(Debug, thiserror::Error)]
pub enum ParseTypedHeaderError {
    /// A specified header is required.
    #[error("header `{0}` is required")]
    HeaderRequired(String),

    /// Parse error.
    #[error("parse: {0}")]
    TypedHeader(#[from] headers::Error),
}

impl ResponseError for ParseTypedHeaderError {
    fn status(&self) -> StatusCode {
        StatusCode::BAD_REQUEST
    }
}

/// A possible error value when handling websocket.
#[cfg(feature = "websocket")]
#[cfg_attr(docsrs, doc(cfg(feature = "websocket")))]
#[derive(Debug, thiserror::Error)]
pub enum WebSocketError {
    /// Invalid protocol
    #[error("invalid protocol")]
    InvalidProtocol,

    /// Upgrade Error
    #[error(transparent)]
    UpgradeError(#[from] UpgradeError),
}

#[cfg(feature = "websocket")]
impl ResponseError for WebSocketError {
    fn status(&self) -> StatusCode {
        match self {
            WebSocketError::InvalidProtocol => StatusCode::BAD_REQUEST,
            WebSocketError::UpgradeError(err) => err.status(),
        }
    }
}

/// A possible error value when upgrading connection.
#[derive(Debug, thiserror::Error)]
pub enum UpgradeError {
    /// No upgrade
    #[error("no upgrade")]
    NoUpgrade,

    /// Other error
    #[error("{0}")]
    Other(String),
}

impl ResponseError for UpgradeError {
    fn status(&self) -> StatusCode {
        match self {
            UpgradeError::NoUpgrade => StatusCode::INTERNAL_SERVER_ERROR,
            UpgradeError::Other(_) => StatusCode::BAD_REQUEST,
        }
    }
}

/// A possible error value when processing static files.
#[derive(Debug, thiserror::Error)]
pub enum StaticFileError {
    /// Method not allow
    #[error("method not found")]
    MethodNotAllowed(Method),

    /// Invalid path
    #[error("invalid path")]
    InvalidPath,

    /// Forbidden
    #[error("forbidden: {0}")]
    Forbidden(String),

    /// File not found
    #[error("not found")]
    NotFound,

    /// Precondition failed
    #[error("precondition failed")]
    PreconditionFailed,

    /// Range not satisfiable
    #[error("range not satisfiable")]
    RangeNotSatisfiable {
        /// Content length
        size: u64,
    },

    /// Io error
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
}

impl ResponseError for StaticFileError {
    fn status(&self) -> StatusCode {
        match self {
            StaticFileError::MethodNotAllowed(_) => StatusCode::METHOD_NOT_ALLOWED,
            StaticFileError::InvalidPath => StatusCode::BAD_REQUEST,
            StaticFileError::Forbidden(_) => StatusCode::FORBIDDEN,
            StaticFileError::NotFound => StatusCode::NOT_FOUND,
            StaticFileError::PreconditionFailed => StatusCode::PRECONDITION_FAILED,
            StaticFileError::RangeNotSatisfiable { .. } => StatusCode::RANGE_NOT_SATISFIABLE,
            StaticFileError::Io(_) => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }

    fn as_response(&self) -> Response {
        let mut resp = Response::builder()
            .status(self.status())
            .body(self.to_string());
        if let StaticFileError::RangeNotSatisfiable { size } = self {
            resp.headers_mut()
                .typed_insert(ContentRange::unsatisfied_bytes(*size));
        }
        resp
    }
}

/// A possible error value occurred in the `SizeLimit` middleware.
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
pub enum SizedLimitError {
    /// Missing `Content-Length` header
    #[error("missing `Content-Length` header")]
    MissingContentLength,

    /// Payload too large
    #[error("payload too large")]
    PayloadTooLarge,
}

impl ResponseError for SizedLimitError {
    fn status(&self) -> StatusCode {
        StatusCode::BAD_REQUEST
    }
}

/// A possible error value occurred when adding a route.
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
pub enum RouteError {
    /// Invalid path
    #[error("invalid path: {0}")]
    InvalidPath(String),

    /// Duplicate path
    #[error("duplicate path: {0}")]
    Duplicate(String),

    /// Invalid regex in path
    #[error("invalid regex in path: {path}")]
    InvalidRegex {
        /// Path
        path: String,

        /// Regex
        regex: String,
    },
}

impl ResponseError for RouteError {
    fn status(&self) -> StatusCode {
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

/// A possible error value occurred when load i18n resources.
#[cfg(feature = "i18n")]
#[derive(Debug, thiserror::Error)]
pub enum I18NError {
    /// Fluent error.
    #[error("fluent: {}", .0[0])]
    Fluent(Vec<fluent::FluentError>),

    /// Fluent FTL parser error.
    #[error("fluent parser: {}", .0[0])]
    FluentParser(Vec<fluent_syntax::parser::ParserError>),

    /// There is no value in the message.
    #[error("no value")]
    FluentNoValue,

    /// Message id was not found.
    #[error("msg not found: `{id}`")]
    FluentMessageNotFound {
        /// Message id
        id: String,
    },

    /// Invalid language id.
    #[error("invalid language id: {0}")]
    LanguageIdentifier(#[from] unic_langid::LanguageIdentifierError),

    /// Io error
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
}

#[cfg(feature = "i18n")]
impl ResponseError for I18NError {
    fn status(&self) -> StatusCode {
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

#[cfg(test)]
mod tests {
    use std::io::{Error as IoError, ErrorKind};

    use super::*;

    #[test]
    fn test_into_result() {
        assert!(matches!("hello".into_result(), Ok("hello")));
        assert!(matches!(Ok::<_, Error>("hello").into_result(), Ok("hello")));
        assert!(matches!(
            Ok::<_, NotFoundError>("hello").into_result(),
            Ok("hello")
        ));
        assert!(Err::<String, _>(NotFoundError)
            .into_result()
            .unwrap_err()
            .is::<NotFoundError>());
    }

    #[test]
    fn test_error() {
        let err = Error::new(
            IoError::new(ErrorKind::AlreadyExists, "aaa"),
            StatusCode::BAD_GATEWAY,
        );
        assert!(err.is::<IoError>());
        assert_eq!(
            err.downcast_ref::<IoError>().unwrap().kind(),
            ErrorKind::AlreadyExists
        );
        assert_eq!(err.as_response().status(), StatusCode::BAD_GATEWAY);
    }

    #[test]
    fn test_box_error() {
        let boxed_err: Box<dyn StdError + Send + Sync> =
            Box::new(IoError::new(ErrorKind::AlreadyExists, "aaa"));
        let err: Error = Error::from((StatusCode::BAD_GATEWAY, boxed_err));
        assert!(err.is::<IoError>());
        assert_eq!(
            err.downcast_ref::<IoError>().unwrap().kind(),
            ErrorKind::AlreadyExists
        );
        assert_eq!(err.as_response().status(), StatusCode::BAD_GATEWAY);
    }

    #[cfg(feature = "anyhow")]
    #[test]
    fn test_anyhow_error() {
        let anyhow_err: anyhow::Error = IoError::new(ErrorKind::AlreadyExists, "aaa").into();
        let err: Error = Error::from((StatusCode::BAD_GATEWAY, anyhow_err));
        assert!(err.is::<IoError>());
        assert_eq!(
            err.downcast_ref::<IoError>().unwrap().kind(),
            ErrorKind::AlreadyExists
        );
        assert_eq!(err.as_response().status(), StatusCode::BAD_GATEWAY);
    }

    #[cfg(feature = "eyre6")]
    #[test]
    fn test_eyre6_error() {
        let eyre6_err: eyre6::Error = IoError::new(ErrorKind::AlreadyExists, "aaa").into();
        let err: Error = Error::from((StatusCode::BAD_GATEWAY, eyre6_err));
        assert!(err.is::<IoError>());
        assert_eq!(
            err.downcast_ref::<IoError>().unwrap().kind(),
            ErrorKind::AlreadyExists
        );
        assert_eq!(err.as_response().status(), StatusCode::BAD_GATEWAY);
    }

    #[tokio::test]
    async fn test_custom_as_response() {
        #[derive(Debug, thiserror::Error)]
        #[error("my error")]
        struct MyError;

        impl ResponseError for MyError {
            fn status(&self) -> StatusCode {
                StatusCode::BAD_GATEWAY
            }

            fn as_response(&self) -> Response {
                Response::builder()
                    .status(self.status())
                    .body("my error message")
            }
        }

        let err = Error::from(MyError);
        let resp = err.as_response();

        assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
        assert_eq!(
            resp.into_body().into_string().await.unwrap(),
            "my error message"
        );
    }
}