主頁 > 後端開發 > Rust Web 全堆疊開發之 Web Service 中的錯誤處理

Rust Web 全堆疊開發之 Web Service 中的錯誤處理

2023-05-31 10:10:55 後端開發

Rust Web 全堆疊開發之 Web Service 中的錯誤處理

Web Service 中的統一錯誤處理

Actix Web Service 自定義錯誤型別 -> 自定義錯誤轉為 HTTP Response

  • 資料庫
    • 資料庫錯誤
  • 串行化
    • serde 錯誤
  • I/O 操作
    • I/O 錯誤
  • Actix-Web 庫
    • Actix 錯誤
  • 用戶非法輸入
    • 用戶非法輸入錯誤

Actix-Web 的錯誤處理

  • 編程語言常用的兩種錯誤處理方式:
    • 例外
    • 回傳值( Rust 使用這種)
  • Rust 希望開發者顯式的處理錯誤,因此,可能出錯的函式回傳Result 列舉型別,其定義如下:
enum Result<T, E> {
  Ok(T),
	Err(E),
}

例子

use std::num::ParseIntError;

fn main() {
  let result = square("25");
  println!("{:?}", result);
}

fn square(val: &str) -> Result<i32, ParseIntError> {
  match val.parse::<i32>() {
    Ok(num) => Ok(num.pow(2)),
    Err(e) => Err(3),
  }
}

? 運算子

  • 在某函式中使用 ? 運算子,該運算子嘗試從 Result 中獲取值:
    • 如果不成功,它就會接收 Error ,中止函式執行,并把錯誤傳播到呼叫該函式的函式,
use std::num::ParseIntError;

fn main() {
  let result = square("25");
  println!("{:?}", result);
}

fn square(val: &str) -> Result<i32, ParseIntError> {
  let num = val.parse::<i32>()?;
  Ok(num ^ 2)
}

自定義錯誤型別

  • 創建一個自定義錯誤型別,它可以是多種錯誤型別的抽象,
  • 例如:
#[derive(Debug)]
pub enum MyError {
  ParseError,
	IOError,
}

Actix-Web 把錯誤轉化為 HTTP Response

  • Actix-Web 定義了一個通用的錯誤型別( struct ):actix_web::error::Error
    • 它實作了 std::error::Error 這個 trait
  • 任何實作了標準庫 Error trait 的型別,都可以通過 ? 運算子,轉化為 Actix 的 Error 型別
  • Actix 的 Error 型別會自動的轉化為 HTTP Response ,回傳給客戶端,
  • ResponseError trait :任何實作該 trait 的錯誤均可轉化為HTTP Response 訊息,
  • 內置的實作: Actix-Web 對于常見錯誤有內置的實作,例如:
  • Rust 標準 I/O 錯誤
  • Serde 錯誤
  • Web 錯誤,例如: ProtocolError 、 Utf8Error 、 ParseError 等等
  • 其它錯誤型別:內置實作不可用時,需要自定義實作錯誤到 HTTP Response 的轉換

創建自定義錯誤處理器

  1. 創建一個自定義錯誤型別
  2. 實作 From trait ,用于把其它錯誤型別轉化為該型別
  3. 為自定義錯誤型別實作 ResponseError trait
  4. 在 handler 里回傳自定義錯誤型別
  5. Actix 會把錯誤轉化為 HTTP 回應

專案目錄

ws on  main [?!?] via ?? 1.67.1 via ?? base 
? tree -a -I target 
.
├── .env
├── .git
├── .gitignore
├── Cargo.lock
├── Cargo.toml
├── README.md
└── webservice
    ├── Cargo.toml
    └── src
        ├── bin
        │   ├── server1.rs
        │   └── teacher-service.rs
        ├── db_access.rs
        ├── errors.rs
        ├── handlers.rs
        ├── main.rs
        ├── models.rs
        ├── routers.rs
        └── state.rs

40 directories, 47 files

ws on  main [?!?] via ?? 1.67.1 via ?? base 

webservice/src/errors.rs

use actix_web::{error, http::StatusCode, HttpResponse, Result};
use serde::Serialize;
use sqlx::error::Error as SQLxError;
use std::fmt;

#[derive(Debug, Serialize)]
pub enum MyError {
    DBError(String),
    ActixError(String),
    NotFound(String),
}
#[derive(Debug, Serialize)]
pub struct MyErrorResponse {
    error_message: String,
}

impl MyError {
    fn error_response(&self) -> String {
        match self {
            MyError::DBError(msg) => {
                println!("Database error occurred: {:?}", msg);
                "Database error".into()
            }
            MyError::ActixError(msg) => {
                println!("Server error occurred: {:?}", msg);
                "Internal server error".into()
            }
            MyError::NotFound(msg) => {
                println!("Not found error occurred: {:?}", msg);
                msg.into()
            }
        }
    }
}

impl error::ResponseError for MyError {
    fn status_code(&self) -> StatusCode {
        match self {
            MyError::DBError(msg) | MyError::ActixError(msg) => StatusCode::INTERNAL_SERVER_ERROR,
            MyError::NotFound(msg) => StatusCode::NOT_FOUND,
        }
    }
    fn error_response(&self) -> HttpResponse {
        HttpResponse::build(self.status_code()).json(MyErrorResponse {
            error_message: self.error_response(),
        })
    }
}

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(f, "{}", self)
    }
}

impl From<actix_web::error::Error> for MyError {
    fn from(err: actix_web::error::Error) -> Self {
        MyError::ActixError(err.to_string())
    }
}

impl From<SQLxError> for MyError {
    fn from(err: SQLxError) -> Self {
        MyError::DBError(err.to_string())
    }
}

webservice/src/bin/teacher-service.rs

use actix_web::{web, App, HttpServer};
use dotenv::dotenv;
use sqlx::postgres::PgPoolOptions;
use std::env;
use std::io;
use std::sync::Mutex;

#[path = "../db_access.rs"]
mod db_access;
#[path = "../errors.rs"]
mod errors;
#[path = "../handlers.rs"]
mod handlers;
#[path = "../models.rs"]
mod models;
#[path = "../routers.rs"]
mod routers;
#[path = "../state.rs"]
mod state;

use routers::*;
use state::AppState;

#[actix_rt::main]
async fn main() -> io::Result<()> {
    dotenv().ok();

    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set.");
    let db_pool = PgPoolOptions::new().connect(&database_url).await.unwrap();

    let shared_data = web::Data::new(AppState {
        health_check_response: "I'm Ok.".to_string(),
        visit_count: Mutex::new(0),
        // courses: Mutex::new(vec![]),
        db: db_pool,
    });
    let app = move || {
        App::new()
            .app_data(shared_data.clone())
            .configure(general_routes)
            .configure(course_routes) // 路由注冊
    };

    HttpServer::new(app).bind("127.0.0.1:3000")?.run().await
}

webservice/src/db_access.rs

use super::errors::MyError;
use super::models::*;
use chrono::NaiveDateTime;
use sqlx::postgres::PgPool;

pub async fn get_courses_for_teacher_db(
    pool: &PgPool,
    teacher_id: i32,
) -> Result<Vec<Course>, MyError> {
    let rows = sqlx::query!(
        r#"SELECT id, teacher_id, name, time FROM course WHERE teacher_id = $1"#,
        teacher_id
    )
    .fetch_all(pool)
    .await?;

    let courses: Vec<Course> = rows
        .iter()
        .map(|row| Course {
            id: Some(row.id),
            teacher_id: row.teacher_id,
            name: row.name.clone(),
            time: Some(NaiveDateTime::from(row.time.unwrap())),
        })
        .collect();

    match courses.len() {
        0 => Err(MyError::NotFound("Courses not found teacher".into())),
        _ => Ok(courses),
    }
}

pub async fn get_courses_detail_db(pool: &PgPool, teacher_id: i32, course_id: i32) -> Course {
    let row = sqlx::query!(
        r#"SELECT id, teacher_id, name, time FROM course WHERE teacher_id = $1 and id = $2"#,
        teacher_id,
        course_id
    )
    .fetch_one(pool)
    .await
    .unwrap();

    Course {
        id: Some(row.id),
        teacher_id: row.teacher_id,
        name: row.name.clone(),
        time: Some(NaiveDateTime::from(row.time.unwrap())),
    }
}

pub async fn post_new_course_db(pool: &PgPool, new_course: Course) -> Course {
    let row = sqlx::query!(
        r#"INSERT INTO course (id, teacher_id, name) VALUES ($1, $2, $3)
        RETURNING id, teacher_id, name, time"#,
        new_course.id,
        new_course.teacher_id,
        new_course.name
    )
    .fetch_one(pool)
    .await
    .unwrap();

    Course {
        id: Some(row.id),
        teacher_id: row.teacher_id,
        name: row.name.clone(),
        time: Some(NaiveDateTime::from(row.time.unwrap())),
    }
}

webservice/src/handlers.rs

use super::db_access::*;
use super::errors::MyError;
use super::state::AppState;
use actix_web::{web, HttpResponse};

pub async fn health_check_handler(app_state: web::Data<AppState>) -> HttpResponse {
    let health_check_response = &app_state.health_check_response;
    let mut visit_count = app_state.visit_count.lock().unwrap();
    let response = format!("{} {} times", health_check_response, visit_count);
    *visit_count += 1;
    HttpResponse::Ok().json(&response)
}

use super::models::Course;

pub async fn new_course(
    new_course: web::Json<Course>,
    app_state: web::Data<AppState>,
) -> HttpResponse {
    let course = post_new_course_db(&app_state.db, new_course.into()).await;
    HttpResponse::Ok().json(course)
}

pub async fn get_courses_for_tescher(
    app_state: web::Data<AppState>,
    params: web::Path<usize>,
) -> Result<HttpResponse, MyError> {
    let teacher_id = i32::try_from(params.into_inner()).unwrap();
    get_courses_for_teacher_db(&app_state.db, teacher_id)
        .await
        .map(|courses| HttpResponse::Ok().json(courses))
}

pub async fn get_courses_detail(
    app_state: web::Data<AppState>,
    params: web::Path<(usize, usize)>,
) -> HttpResponse {
    let teacher_id = i32::try_from(params.0).unwrap();
    let course_id = i32::try_from(params.1).unwrap();
    let course = get_courses_detail_db(&app_state.db, teacher_id, course_id).await;
    HttpResponse::Ok().json(course)
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::http::StatusCode;
    use dotenv::dotenv;
    use sqlx::postgres::PgPoolOptions;
    use std::env;
    use std::sync::Mutex;

    #[actix_rt::test] // 異步測驗
    async fn post_course_test() {
        dotenv().ok();
        let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set");
        let db_pool = PgPoolOptions::new().connect(&db_url).await.unwrap();
        let app_state: web::Data<AppState> = web::Data::new(AppState {
            health_check_response: "".to_string(),
            visit_count: Mutex::new(0),
            db: db_pool,
        });

        let course = web::Json(Course {
            teacher_id: 1,
            name: "Test course".into(),
            id: Some(3), // serial
            time: None,
        });

        let resp = new_course(course, app_state).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[actix_rt::test]
    async fn get_all_courses_success() {
        dotenv().ok();
        let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set");
        let db_pool = PgPoolOptions::new().connect(&db_url).await.unwrap();
        let app_state: web::Data<AppState> = web::Data::new(AppState {
            health_check_response: "".to_string(),
            visit_count: Mutex::new(0),
            db: db_pool,
        });
        let teacher_id: web::Path<usize> = web::Path::from(1);
        let resp = get_courses_for_tescher(app_state, teacher_id)
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[actix_rt::test]
    async fn get_one_course_success() {
        dotenv().ok();
        let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set");
        let db_pool = PgPoolOptions::new().connect(&db_url).await.unwrap();
        let app_state: web::Data<AppState> = web::Data::new(AppState {
            health_check_response: "".to_string(),
            visit_count: Mutex::new(0),
            db: db_pool,
        });
        let params: web::Path<(usize, usize)> = web::Path::from((1, 1));
        let resp = get_courses_detail(app_state, params).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }
}

測驗

ws on  main via ?? 1.67.1 via ?? base 
? cargo test --bin teacher-service get_all_courses_success
   Compiling webservice v0.1.0 (/Users/qiaopengjun/rust/ws/webservice)
warning: unused variable: `msg`
  --> webservice/src/bin/../errors.rs:39:30
   |
39 |             MyError::DBError(msg) | MyError::ActixError(msg) => StatusCode::INTERNAL_SERVER_ERROR,
   |                              ^^^                        ^^^
   |
   = note: `#[warn(unused_variables)]` on by default
help: if this is intentional, prefix it with an underscore
   |
39 |             MyError::DBError(_msg) | MyError::ActixError(_msg) => StatusCode::INTERNAL_SERVER_ERROR,
   |                              ~~~~                        ~~~~

warning: unused variable: `msg`
  --> webservice/src/bin/../errors.rs:40:31
   |
40 |             MyError::NotFound(msg) => StatusCode::NOT_FOUND,
   |                               ^^^ help: if this is intentional, prefix it with an underscore: `_msg`

warning: `webservice` (bin "teacher-service" test) generated 2 warnings (run `cargo fix --bin "teacher-service" --tests` to apply 2 suggestions)
    Finished test [unoptimized + debuginfo] target(s) in 1.55s
     Running unittests src/bin/teacher-service.rs (target/debug/deps/teacher_service-32d6a48d6ee3c4b4)

running 1 test
test handlers::tests::get_all_courses_success ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.01s


ws on  main [?!?] via ?? 1.67.1 via ?? base took 2.1s 
? 

webservice/src/db_access.rs

use super::errors::MyError;
use super::models::*;
use chrono::NaiveDateTime;
use sqlx::postgres::PgPool;

pub async fn get_courses_for_teacher_db(
    pool: &PgPool,
    teacher_id: i32,
) -> Result<Vec<Course>, MyError> {
    let rows = sqlx::query!(
        r#"SELECT id, teacher_id, name, time FROM course WHERE teacher_id = $1"#,
        teacher_id
    )
    .fetch_all(pool)
    .await?;

    let courses: Vec<Course> = rows
        .iter()
        .map(|row| Course {
            id: Some(row.id),
            teacher_id: row.teacher_id,
            name: row.name.clone(),
            time: Some(NaiveDateTime::from(row.time.unwrap())),
        })
        .collect();

    match courses.len() {
        0 => Err(MyError::NotFound("Courses not found teacher".into())),
        _ => Ok(courses),
    }
}

pub async fn get_courses_detail_db(
    pool: &PgPool,
    teacher_id: i32,
    course_id: i32,
) -> Result<Course, MyError> {
    let row = sqlx::query!(
        r#"SELECT id, teacher_id, name, time FROM course WHERE teacher_id = $1 and id = $2"#,
        teacher_id,
        course_id
    )
    .fetch_one(pool)
    .await;

    if let Ok(row) = row {
        Ok(Course {
            id: Some(row.id),
            teacher_id: row.teacher_id,
            name: row.name.clone(),
            time: Some(NaiveDateTime::from(row.time.unwrap())),
        })
    } else {
        Err(MyError::NotFound("Course Id not found".into()))
    }
}

pub async fn post_new_course_db(pool: &PgPool, new_course: Course) -> Result<Course, MyError> {
    let row = sqlx::query!(
        r#"INSERT INTO course (id, teacher_id, name) VALUES ($1, $2, $3)
        RETURNING id, teacher_id, name, time"#,
        new_course.id,
        new_course.teacher_id,
        new_course.name
    )
    .fetch_one(pool)
    .await?;

    Ok(Course {
        id: Some(row.id),
        teacher_id: row.teacher_id,
        name: row.name.clone(),
        time: Some(NaiveDateTime::from(row.time.unwrap())),
    })
}

webservice/src/handlers.rs

use super::db_access::*;
use super::errors::MyError;
use super::state::AppState;
use actix_web::{web, HttpResponse};

pub async fn health_check_handler(app_state: web::Data<AppState>) -> HttpResponse {
    let health_check_response = &app_state.health_check_response;
    let mut visit_count = app_state.visit_count.lock().unwrap();
    let response = format!("{} {} times", health_check_response, visit_count);
    *visit_count += 1;
    HttpResponse::Ok().json(&response)
}

use super::models::Course;

pub async fn new_course(
    new_course: web::Json<Course>,
    app_state: web::Data<AppState>,
) -> Result<HttpResponse, MyError> {
    post_new_course_db(&app_state.db, new_course.into())
        .await
        .map(|course| HttpResponse::Ok().json(course))
}

pub async fn get_courses_for_tescher(
    app_state: web::Data<AppState>,
    params: web::Path<usize>,
) -> Result<HttpResponse, MyError> {
    let teacher_id = i32::try_from(params.into_inner()).unwrap();
    get_courses_for_teacher_db(&app_state.db, teacher_id)
        .await
        .map(|courses| HttpResponse::Ok().json(courses))
}

pub async fn get_courses_detail(
    app_state: web::Data<AppState>,
    params: web::Path<(usize, usize)>,
) -> Result<HttpResponse, MyError> {
    let teacher_id = i32::try_from(params.0).unwrap();
    let course_id = i32::try_from(params.1).unwrap();
    get_courses_detail_db(&app_state.db, teacher_id, course_id)
        .await
        .map(|course| HttpResponse::Ok().json(course))
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::http::StatusCode;
    use dotenv::dotenv;
    use sqlx::postgres::PgPoolOptions;
    use std::env;
    use std::sync::Mutex;

    #[ignore]
    #[actix_rt::test] // 異步測驗
    async fn post_course_test() {
        dotenv().ok();
        let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set");
        let db_pool = PgPoolOptions::new().connect(&db_url).await.unwrap();
        let app_state: web::Data<AppState> = web::Data::new(AppState {
            health_check_response: "".to_string(),
            visit_count: Mutex::new(0),
            db: db_pool,
        });

        let course = web::Json(Course {
            teacher_id: 1,
            name: "Test course".into(),
            id: Some(5), // serial
            time: None,
        });

        let resp = new_course(course, app_state).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[actix_rt::test]
    async fn get_all_courses_success() {
        dotenv().ok();
        let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set");
        let db_pool = PgPoolOptions::new().connect(&db_url).await.unwrap();
        let app_state: web::Data<AppState> = web::Data::new(AppState {
            health_check_response: "".to_string(),
            visit_count: Mutex::new(0),
            db: db_pool,
        });
        let teacher_id: web::Path<usize> = web::Path::from(1);
        let resp = get_courses_for_tescher(app_state, teacher_id)
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[actix_rt::test]
    async fn get_one_course_success() {
        dotenv().ok();
        let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set");
        let db_pool = PgPoolOptions::new().connect(&db_url).await.unwrap();
        let app_state: web::Data<AppState> = web::Data::new(AppState {
            health_check_response: "".to_string(),
            visit_count: Mutex::new(0),
            db: db_pool,
        });
        let params: web::Path<(usize, usize)> = web::Path::from((1, 1));
        let resp = get_courses_detail(app_state, params).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }
}

測驗

ws on  main [?!?] via ?? 1.67.1 via ?? base took 2.1s 
? cargo test --bin teacher-service                           
   Compiling webservice v0.1.0 (/Users/qiaopengjun/rust/ws/webservice)
warning: unused variable: `msg`
  --> webservice/src/bin/../errors.rs:39:30
   |
39 |             MyError::DBError(msg) | MyError::ActixError(msg) => StatusCode::INTERNAL_SERVER_ERROR,
   |                              ^^^                        ^^^
   |
   = note: `#[warn(unused_variables)]` on by default
help: if this is intentional, prefix it with an underscore
   |
39 |             MyError::DBError(_msg) | MyError::ActixError(_msg) => StatusCode::INTERNAL_SERVER_ERROR,
   |                              ~~~~                        ~~~~

warning: unused variable: `msg`
  --> webservice/src/bin/../errors.rs:40:31
   |
40 |             MyError::NotFound(msg) => StatusCode::NOT_FOUND,
   |                               ^^^ help: if this is intentional, prefix it with an underscore: `_msg`

warning: `webservice` (bin "teacher-service" test) generated 2 warnings (run `cargo fix --bin "teacher-service" --tests` to apply 2 suggestions)
    Finished test [unoptimized + debuginfo] target(s) in 1.27s
     Running unittests src/bin/teacher-service.rs (target/debug/deps/teacher_service-32d6a48d6ee3c4b4)

running 3 tests
test handlers::tests::get_one_course_success ... ok
test handlers::tests::get_all_courses_success ... ok
test handlers::tests::post_course_test ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s


ws on  main [?!?] via ?? 1.67.1 via ?? base 
? 


ws on  main [?!?] via ?? 1.67.1 via ?? base 
? cargo test --bin teacher-service                        
   Compiling webservice v0.1.0 (/Users/qiaopengjun/rust/ws/webservice)
warning: unused variable: `msg`
  --> webservice/src/bin/../errors.rs:39:30
   |
39 |             MyError::DBError(msg) | MyError::ActixError(msg) => StatusCode::INTERNAL_SERVER_ERROR,
   |                              ^^^                        ^^^
   |
   = note: `#[warn(unused_variables)]` on by default
help: if this is intentional, prefix it with an underscore
   |
39 |             MyError::DBError(_msg) | MyError::ActixError(_msg) => StatusCode::INTERNAL_SERVER_ERROR,
   |                              ~~~~                        ~~~~

warning: unused variable: `msg`
  --> webservice/src/bin/../errors.rs:40:31
   |
40 |             MyError::NotFound(msg) => StatusCode::NOT_FOUND,
   |                               ^^^ help: if this is intentional, prefix it with an underscore: `_msg`

warning: `webservice` (bin "teacher-service" test) generated 2 warnings (run `cargo fix --bin "teacher-service" --tests` to apply 2 suggestions)
    Finished test [unoptimized + debuginfo] target(s) in 0.71s
     Running unittests src/bin/teacher-service.rs (target/debug/deps/teacher_service-32d6a48d6ee3c4b4)

running 3 tests
test handlers::tests::post_course_test ... ignored
test handlers::tests::get_one_course_success ... ok
test handlers::tests::get_all_courses_success ... ok

test result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.01s


ws on  main [?!?] via ?? 1.67.1 via ?? base 
? 

本文來自博客園,作者:QIAOPENGJUN,轉載請注明原文鏈接:https://www.cnblogs.com/QiaoPengjun/p/17445127.html

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/553920.html

標籤:其他

上一篇:驅動開發:內核決議PE結構匯出表

下一篇:返回列表

標籤雲
其他(160062) Python(38189) JavaScript(25466) Java(18163) C(15235) 區塊鏈(8268) C#(7972) AI(7469) 爪哇(7425) MySQL(7219) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5873) 数组(5741) R(5409) Linux(5344) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4580) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2434) ASP.NET(2403) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) .NET技术(1979) 功能(1967) Web開發(1951) HtmlCss(1950) C++(1928) python-3.x(1918) 弹簧靴(1913) xml(1889) PostgreSQL(1879) .NETCore(1863) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust Web 全堆疊開發之 Web Service 中的錯誤處理

    # Rust Web 全堆疊開發之 Web Service 中的錯誤處理 ## Web Service 中的統一錯誤處理 ### Actix Web Service 自定義錯誤型別 -> 自定義錯誤轉為 HTTP Response - 資料庫 - 資料庫錯誤 - 串行化 - serde 錯誤 - I/ ......

    uj5u.com 2023-05-31 10:10:55 more
  • 驅動開發:內核決議PE結構匯出表

    在筆者的上一篇文章`《驅動開發:內核特征碼掃描PE代碼段》`中`LyShark`帶大家通過封裝好的`LySharkToolsUtilKernelBase`函式實作了動態獲取內核模塊基址,并通過`ntimage.h`頭檔案中提供的系列函式決議了指定內核模塊的`PE節表`引數,本章將繼續延申這個話題,實... ......

    uj5u.com 2023-05-31 10:10:44 more
  • keycloak~自定義登出介面

    keycloak提供了登出的介面,不過它是一個post方法,需要你根據client_id,client_secret及refresh_token進行登出操作的,有時不太靈活,所以我又自己封裝了一下,通過客戶端瀏覽器上存盤的session_id進行會話登出。 # kc提供的logout * api:{ ......

    uj5u.com 2023-05-31 10:10:35 more
  • Java中泛型詳解,非常詳細

    # 前言 在前面的幾篇文章中,詳細地給大家介紹了Java里的集合。但在介紹集合時,我們涉及到了泛型的概念卻并沒有詳細學習,**所以今天我們要花點時間給大家專門講解什么是泛型、泛型的作用、用法、特點等內容。** 有些粉絲朋友,在之前就一直很好奇,比如List中的 部分到底是什么?有啥用?為什么要加這個 ......

    uj5u.com 2023-05-31 10:09:33 more
  • keycloak~自定義登出介面

    keycloak提供了登出的介面,不過它是一個post方法,需要你根據client_id,client_secret及refresh_token進行登出操作的,有時不太靈活,所以我又自己封裝了一下,通過客戶端瀏覽器上存盤的session_id進行會話登出。 # kc提供的logout * api:{ ......

    uj5u.com 2023-05-31 10:09:26 more
  • 驅動開發:內核決議PE結構匯出表

    在筆者的上一篇文章`《驅動開發:內核特征碼掃描PE代碼段》`中`LyShark`帶大家通過封裝好的`LySharkToolsUtilKernelBase`函式實作了動態獲取內核模塊基址,并通過`ntimage.h`頭檔案中提供的系列函式決議了指定內核模塊的`PE節表`引數,本章將繼續延申這個話題,實... ......

    uj5u.com 2023-05-31 10:03:24 more
  • Java中如何中斷執行緒

    在Java中,可以使用以下方法中斷執行緒: 1. 使用`interrupt()`方法:每個執行緒物件都有一個`interrupt()`方法,用于中斷該執行緒。當呼叫執行緒的`interrupt()`方法時,它會設定執行緒的中斷狀態為"中斷",但并不會立即停止執行緒的執行。執行緒在執行程序中可以通過檢查中斷狀態來決 ......

    uj5u.com 2023-05-31 08:14:02 more
  • java注解與反射

    # java注解與反射 - java注解與反射十分重要,是很多框架的底層 ## 注解(Annotataion) - 注解的作用: 1. 不是程式本身,可以對程式作出解釋 1. 可以被其他程式讀取 - 注解的格式:@注釋名,如@override表示重寫方法,而且有些還可以添加一些引數值,如@Suppr ......

    uj5u.com 2023-05-31 08:08:28 more
  • Python連接es筆記三之es更新操作

    > 本文首發于公眾號:Hunter后端 > 原文鏈接:[Python連接es筆記三之es更新操作](https://mp.weixin.qq.com/s/1cTaVfjLFrmbXajNcayhEA) 這一篇筆記介紹如何使用 Python 對資料進行更新操作。 對于 es 的更新的操作,不用到 Se ......

    uj5u.com 2023-05-31 08:03:03 more
  • 騰訊二面:有 40 億個 QQ 號,限制 1G 記憶體,問如何去重?被問懵了!

    > 40億個QQ號,限制1G記憶體,如何去重? 40億個unsigned int,如果直接用記憶體存盤的話,需要: `4*4000000000 /1024/1024/1024 = 14.9G` ,考慮到其中有一些重復的話,那1G的空間也基本上是不夠用的。 想要實作這個功能,可以借助位圖。 使用位圖的話, ......

    uj5u.com 2023-05-31 07:56:52 more