D
D
Dmitry Baibukhtin2015-03-12 17:19:38
PHP
Dmitry Baibukhtin, 2015-03-12 17:19:38

How to return an error code from a method?

Good evening. Please tell me the best way to return an error code from a method.
For example, there is a function:

/**
     * @return User|bool
     */
    public function register()
    {
      //  ...
        if (empty($userData)) {
            $errorCode = $this::USER_DATA_EMPTY_ERROR;
        } else if ($this->authenticate() === true) {
            $errorCode = $this::USER_REGISTERED_ERROR;
        } else {
            return $registeredUser;
        }
    }

Options:
  1. Return true or an error code, but may cause serious problems in the future. Let's say if we forgot to write a strict comparison ===
  2. Throw an exception. This is more of a fatal error, so it doesn't fit.
  3. Writing an error code to a property of the object that contains the method. Good option, but don't want to clutter up the class

How are you doing?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2015-03-12
@PiloTeZ

If an exception is caught, then it does not apply to fatal errors.

A
Armenian Radio, 2015-03-12
@gbg

Fatal errors rather include thinking that exceptions are needed only to work out some kind of horror. In fact, this is the most correct language mechanism, the correct application of which guarantees the correct unwinding and cleaning of the stack, as well as the release of resources, especially when using complex, dynamic resource capture logic.

A
Andrey Burov, 2015-03-12
@BuriK666

Return true or an error code, but may cause serious problems in the future. Let's say if we forgot to write a strict comparison ===
If someone forgot something or doesn't know, that's his problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question