Create custom exception handler


Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

PHP has an exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling.


There are following functions which can be used from Exception class.
  • getMessage()- message of exception
  • getCode() - code of exception
  • getFile() - source filename
  • getLine() - source line
  • getTrace() - n array of the backtrace()
  • getTraceAsString() - formated string of trace


<?php
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

In the above example $e->getMessage function is uded to get error 
message. 


All errors and warnings should be logged. Based on the severity of an error, notifications should be sent out to other systems/teams. So that you can better gauge its severity, PHP provides several built-in error levels to describe the nature of an error. Each level is represented by an integer value and named constant which can be used by the programmer.  

The following table is generated from http://php.net/manual/en/errorfunc.constants.php





You can extend PHP's built in Exception class and create custom Exception handler for more flexibility.

Here I have created a custom exception handler

<?php
error_reporting(E_ALL);
// error_reporting(E_ALL | E_STRICT);  // From PHP 5.4.0 E_STRICT is a part of E_ALL

class NoticeException extends Exception { 
    public function __toString() {
        return  "NOTICE :: $this->message";
    }
}

class WarningException extends Exception { 
    public function __toString() {
        return  "WARNING :: $this->message";
    }
}

class StrictException extends Exception {
    public function __toString() {
        return  "STRICT :: $this->message";
    }
}

class UserThrownException extends Exception {
    public function __toString() {
        return "USER ERROR :: $this->message";
    }
}

class UserDepricatedException extends Exception {
    public function __toString() {
        return "USER DEPRICATED ERROR :: $this->message";
    }
}

class OtherErrorException extends Exception {
    public function __toString() {
        return  "OTHER ERROR :: $this->message";
    }
}

function pc_error_handler($errno,$error,$file,$line,$context) {
    $message = "[$error][FILE : $file][LINE : $line]";
    
    if($errno == E_WARNING) {
        throw new WarningException($message);
    } else if($errno == E_NOTICE) {
        throw new NoticeException($message);
    } else if($errno == E_STRICT) {
        throw new StrictException($message);
    } else if($errno == E_USER_ERROR) {
        throw new UserThrownException($message);
    } else if($errno == E_USER_DEPRECATED) {
        throw new UserDepricatedException($message);
    } else {
        throw new OtherErrorException($message);
    }
}

32 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Absolutely fabulous! Thanks for giving out excellent information. Your post is fascinating and I have forwarded it to some of my links.
    online college papers

    ReplyDelete
  3. Great article! This is the type of information that are meant to be public around the internet.
    college paper writing services

    ReplyDelete
  4. Really appreciate the Collective Impact concepts. I'm impressed by the details that you have on this web site. This is really very beneficial site. write my college essay

    ReplyDelete
  5. Great publish, very useful information. I really appreciate this post. You must continue your writing. I'm confident, you've a huge readers' base already!
    Engineering Colleges in Chennai, ECE Engineering Colleges in Chennai

    ReplyDelete
  6. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

    Texting API
    Text message marketing
    Digital Mobile Marketing
    Mobile Marketing Services
    Mobile marketing companies
    Fitness SMS

    ReplyDelete
  7. Nice site....Please refer this site also Our vision success!Training are focused on perfect improvement of technical skills for Freshers and working professional. Our Training classes are sure to help the trainee with COMPLETE PRACTICAL TRAINING and Real time methodologies
    Dot Net Training in Chennai | Dot Net Training Institute in Chennai
    Software Testing Training in Chennai | Software Testing Course in Chennai
    Java Training Institute in Chennai | Core Java Training in Chennai | Java Course and Certification
    PHP Course in Chennai | PHP Certification in chennai | PHP Training Institutes

    ReplyDelete
  8. It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.
    Data science Course Training in Chennai |Best Data Science Training Institute in Chennai
    matlab training chennai | Matlab course in chennai

    ReplyDelete
  9. Clinical sas training in chennai | SAS Training course chennai
    I have to voice my passion for your kindness giving support to those people that should have guidance on this important matter.

    ReplyDelete
  10. It’s always so sweet and also full of a lot of fun for me personally and my office colleagues to search your blog a minimum of thrice in a week to see the new guidance you have got.


    Best PHP Training Institute in Chennai|PHP Course in chennai

    Best .Net Training Institute in Chennai

    Powerbi Training in Chennai
    R Programming Training in Chennai
    Javascript Training in Chennai

    ReplyDelete
  11. Really it is very useful for us..... the information that you have shared is really useful for everyone.Nice article i have ever read information's like this.it's really awesome the way you have delivered your ideas.i hope you will add more content in your blog
    Java Training in Chennai

    Java Training in Velachery

    Java Training in Tambaram

    Java Training in Porur

    Java Training in Omr

    Java Training in Annanagar

    ReplyDelete
  12. This avocado is probably a good Herbal Supplement for Granuloma Annulare because that works on granuloma annulare which is packed with vitamin E. You can also take a daily tablespoon of apple cider vinegar verbally or apply it to your skin as they are a Granuloma Annulare Natural Treatment. Coconut oil absorbs into the skin and penetrates very effectively - Granuloma Annulare Coconut Oil will help relieve any itching and inflammation from your rash.

    ReplyDelete
  13. You should drink green tea on a regular basis because this can effective in the Natural Remedies for Granuloma Annulare natural recovery. There is another way to use green tea and that is to apply the green tea bags to your skin directly. Green Tea has anti-inflammatory and antioxidant properties which can help in the healing process.

    ReplyDelete
  14. Very Informative blog thank you for sharing. Keep sharing.

    Best software training institute in Chennai. Make your career development the best by learning software courses.

    blue prism training chennai
    power bi training in chennai
    rpa training in chennai

    ReplyDelete
  15. Bonus Code for NEWEST CASINO COUNCIL REVIEW - Casino Roll
    This 슬롯 추천 bonus code will 바카라규칙 be 벤 델핀 activated on registration. If you have received the welcome 바카라필승법 offer from 유로 스타 도메인 our website on your first visit,

    ReplyDelete

  16. Natural Treatment for Actinic Keratosis is to prevent the lesions from turning into skin cancers. Herbal Supplement used to treat or reduce the symptoms.

    ReplyDelete
  17. Natural Remedies for Burning Mouth Syndrome Options (2013). According to his experience,
    Changing your diet can have a tremendous impact on your burning mouth syndrome symptoms.One quick remedy is taking Breneton; it’s an Herbal Supplement for Burning Mouth Syndrome that’s extremely effective at treating and reducing burning mouth syndrome symptoms. how much pain and discomfort you’re experiencing and other things associated with burning mouth syndrome. Note your symptoms before taking Herbal Supplements.

    ReplyDelete
  18. One of several ways you can treat granuloma annulare is using a potent and effective Herbal Remedies for Granuloma Annulare. Herbal supplements for granuloma annulare include milk thistle, borage oil, dandelion root, red clover extract, burdock root, white willow bark, and St. John’s wort, among others. It would help if you chose a 100% natural herbal supplement that contains only pure herbs without fillers or additives.

    ReplyDelete
  19. The typical symptom of Hydrocele is enlargement or swelling around a testicle.The Natural Remedies for Hydrocele involves surgery to correct any anatomical defect in your child’s scrotum. These additional Herbal Remedies for Hydrocele include herbal medicine like Celdeton Hydrocele.Natural Cure Zone strongly recommends that you consult with your primary healthcare provider before starting any Herbal Supplements.Herbal Supplement for Hydrocele can be treated naturally with herbal supplements.

    ReplyDelete
  20. Herbal Supplement for Emphysema Helps Boost Energy Levels: If you or a loved one is suffering from shortness of breath caused by lung diseaseNatural Treatment for Emphysema may include oregano, an herb with powerful antioxidant properties.Thyme is a Natural Remedies for Emphysema.Rosemary is used in Herbal Remedies for Emphysema to help protect healthy cells from damage, improving lung function.

    ReplyDelete
  21. Ginger is used as Natural Remedies for Abdominal Adhesions,Turmeric is a well-known herb and Natural Treatment for Abdominal Adhesions discomfort, which can be caused by a variety of factors.It has antispasmodic, cardioprotective, and heart muscle strengthening effects, and it is also Alternative Treatment for Abdominal Adhesions.Herbal Supplement for Abdominal Adhesions, you should seek medical attention.

    ReplyDelete
  22. Do you suffer from skin disease? Herbal Remedies for Skin Disease is the best herbal Skin Care Products for you. It will not only treat your skin disease but also make your skin look healthy and beautiful.

    ReplyDelete