mardi 26 avril 2016

Need help designing a better way of handling user errors

I have created a file that contains all my validation functions. They are being called multiple times all over my application. Here are some of them.

Note: I am using php, but I don't think it matters that much.

// check if uploaded file is valid:
function validate_file($full_path, $error_code) {
    if (is_file($full_path)) {
        throw new Exception('This file already exist.');
    }
    if ($error_code != 0) {
        throw new Exception($error_code);
    }
}

// get all database specific errors after each sql operation
public function get_db_errors() {
    $message = $this->db->_error_message();
    if (!empty($message)) {
        throw new Exception($message);
    }
}

// add unique record to the database
public function insert($table_name, $columns, $unique_columns = null) {
    if ($unique_columns == null || empty($this->get($table_name, $unique_columns))) {
        $this->db->insert($table_name, $columns);
    } else {
        throw new Exception('this ' .key($unique_columns) . ' already exist.');
    }
    $this->get_db_errors();
}

Here's how I can use them:

class controller {
    try {
        // call any function above if needed.
    } catch(Exception $e) {
        $e->getMessage();
    }
}

I'm pretty happy using this code, since I have one error handler that catches any exception my helper functions can throw. I can even do this in any controller. Until I've read that putting everything in exceptions is actually not the preferred way of handling bad inputs.

Obviously, I will have to destroy all those functions and create a new error handling mechanism for my application. The thing is now I have no idea how to proceed.

How can I proceed designing a user error handler while remaining simple as before? I've heard that one option is to put all error messages in an array and give each of them an error_code. Is that the preferred solution?

Aucun commentaire:

Enregistrer un commentaire