CodeIgniter创建新的自定义异常

时间:2013-04-22 11:00:18

标签: php codeigniter exception

我正在尝试创建自定义异常,以便根据$_FILES[..]['error']代码返回正确的消息。

我扩展了CI_Exceptions class

class MY_Exceptions extends CI_Exceptions {
    function My_Exceptions() {
        parent::CI_Exceptions();
    }

    public function file_upload_error($error_code = UPLOAD_ERR_OK) {
        switch ($error_code) {
            case UPLOAD_ERR_INI_SIZE:
                $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
                break;
            case UPLOAD_ERR_PARTIAL:
                $message = "The uploaded file was only partially uploaded";
                break;
            case UPLOAD_ERR_NO_FILE:
                $message = "No file was uploaded";
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $message = "Missing a temporary folder";
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $message = "Failed to write file to disk";
                break;
            case UPLOAD_ERR_EXTENSION:
                $message = "File upload stopped by extension";
                break;

            default:
                $message = "Unknown upload error";
                break;
        }

        log_message('error', $error_code);
        return $message;
    }    
}

但是当我致电file_upload_error(1)时,它会说Call to undefined function file_upload_error()

如何处理此问题?

1 个答案:

答案 0 :(得分:2)

我觉得你没有正确使用你的图书馆课程,但很难从你的问题中看出来。从模型或控制器类中,您将使用:

$this->load->library('exceptions');
$message = $this->exceptions->file_upload_error($error_code);

当你告诉它加载异常库时,它会自动查看你的application / libraries /目录中是否有一个MY_前缀。如果它在那里,它将加载它。然后您可以像访问任何其他库一样访问它。

希望有所帮助。