27
Subject: Errorhandling and logging Main points: 1: Error handling: programmer, user and hardware errors 2: Recover from error 3: Log and respond to user

Subject: Errorhandling and logging

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Subject: Errorhandling and logging

Subject: Errorhandling and loggingMain points:1: Error handling: programmer, user and hardware errors2: Recover from error3: Log and respond to user

Page 2: Subject: Errorhandling and logging

Agenda P1 part 1:

● Status with class (10 min)● 3 types of errors (25 min)● Class exercise: validate user input (10 min.)● Break 10 min.

P2● Recover from error (25 min)● Class exercise: catch error and handle it (15 min.)● Break 10 min.

P3● Log error and respond error to user (25 min)● Class exercise: implement Logger and write to fle

P4● Work on daily exercise

Page 3: Subject: Errorhandling and logging

Section 1: Error handling

Subjects:1: What are errors in a computer program2: Exceptions: Checked and unchecked 3: Write own domain specifc exceptions

Page 4: Subject: Errorhandling and logging

Section 1: topic - 25 minutes slides:1) What are errors?2) Why do errors happen?3) Types of errors4) What to do about errors?5) Exceptions

1) Unchecked / Checked

2) Throws / Try-Catch-Finally

3) Throw

4) Custom / Extends / Methods

Page 5: Subject: Errorhandling and logging

Slide 1: What are errors

● When the code produces erroneous results:

● 2 + 2 = 5

● 404 not found

Page 6: Subject: Errorhandling and logging

Slide 2: WHY DO ERRORS HAPPEN? When the code generate errors it can happen for 3 reasons

1. The programmer made a mistake2. The environment changed unexpectedly3. The program user has made a mistake

Page 7: Subject: Errorhandling and logging

Slide 3: BAD CODING In this frst case the programmer has made a mistake:

Syntax errors: Language syntax is not respectedSemantic errors: Improper use of program statementsLogical errors: Undesired behaviorCompile time errors: Syntax errors and static semantic errors indicated by the compilerRuntime errors: Dynamic semantic errors and logical errors, that cannot be detected by the compiler

Examples:- divide by zero- index out of bound etc.- nullpointer exception

Page 8: Subject: Errorhandling and logging

Slide 4: ENVIRONMENT PROBLEMS ● In the second case some physical resource has failed

in some way.● Errors include:

– internet connection was lost

– disk error etc.

– database server not running

– Etc.

Page 9: Subject: Errorhandling and logging

Slide 5: USER INITIATED ERRORS In the third case the user has made an errorE.g.:

- 403 forbidden - when trying to access a protected resource- NumberFormatException - when putting letters in a number feld in a form- etc.

Page 10: Subject: Errorhandling and logging

Slide 6: WHAT TO DO ABOUT ERRORS?

● Errors should be handled

● User should be notifed

● Log fles should be updated

● Program should continue

Page 11: Subject: Errorhandling and logging

Slide 7: Handle user input?

● User input to the server should be controlled before passing on to any methods that expects a particular datatype or content

● Check for

– Null● if(username != null){...}

– Empty string● if(comments.length == 0){...}

– Characters (numbers, special chars, email etc.)● Use regular expressions like:

import java.util.regex.*;

if (!Pattern.matches("[a-zA-ZæøåÆØÅ0-9 ]{2,30}", phone)) {...}

Page 12: Subject: Errorhandling and logging

Class exercise 1: Handle user input● In a new maven webproject: Create a jsp page with a web form consisting of

html elements:

1) An input feld for phone numbers (only allow 8 digits with no spaces)

2) A text area (allow only alphanumeric characters)

3) 2 radio buttons (precoded values)

4) 3 checkboxes (precoded values

5) A selectbox with 4 items to choose from (precoded values)

6) A submit buttom that sends a POST request to a servlet with all the data.

Html form if you dont want to do it yourself

● In the servlet extract all the data from the request (all parameters) and make sure data has the right datatypes and format

● 1: allow only 8 digits

● 2: allow only alphanumeric characters

● 3-5: allow only the precoded values (no other values are acceptable)

● Finally: If any data violates the rules, then report back to the user.

Page 13: Subject: Errorhandling and logging

Section 2: Recover from errors

Subjects:1: Compiletime exceptions and runtime exceptions 2: Catching and throwing exceptions3: Create custom domain exception

Page 14: Subject: Errorhandling and logging

Slide 1: ExceptionsWhen an exception occur the normal flow of the program is disrupted and the program/application terminates abnormally, which is not recommended, therefore, exceptions should be handled.

Page 15: Subject: Errorhandling and logging

Slide 2: Unchecked ● UNCHECKED EXCEPTIONS

– Unchecked exceptions occur at run time

– The code will compile even though code throws an exception

– These exceptions mostly comes from bad data from the user

– These exceptions are direct sub classes of RuntimeException class int result = 2/0; This will throw an arithmeticException, but it will compile

Page 16: Subject: Errorhandling and logging

Slide 3: Checked ● CHECKED EXCEPTIONS

– Checked exceptions occur at compile time

– These are also called ‘compile time exceptions’.

– These exceptions cannot be ignored at the time of compilation

– The programmer must take care of these exceptions

– Netbeans message: “Exception must be caught or declared to be thrown”:

● Examples:

– FileNotFoundException

– IOException

– SQLException

Page 17: Subject: Errorhandling and logging

Slide 4: How to handle checked● 2 options

1. Catch and do something

2. Throw back to calling method

● Do not● Catch an exception and do nothing!!!!

Page 18: Subject: Errorhandling and logging

Slide 5: TRY-CATCH-FINALLY● try: one or more statements if any exceptions are thrown then

● catch: the exception and do some damage control

● fnally: run some statements in either case (e.g: closing down resources)

● Multiple catch types

● Diferent exceptions can be caught in a single catch

catch (NumberFormatException | ArithmeticException ex){}

● Use the diferent exception methods

e.printStackTrace()

e.getMessage()

e.getStackTrace()[]

Page 19: Subject: Errorhandling and logging

Slide 6: Throw exception back● Throw exception back to the calling method

● Show example

Page 20: Subject: Errorhandling and logging

Slide 7: Create new custom exception

● In netbeans use the wizard

● Extend the super class Exception to get a checked exception.

Page 21: Subject: Errorhandling and logging

Slide 8: Donts

● Remember never to catch an exception and silently swallow it.

Page 22: Subject: Errorhandling and logging

Excercise 2: Custom exception1. In your exercise project from Exercise 1, create a new Custom

Exception2. Create a DB class that can return a DB connection with url,

credentiels and driver3. Create a mapper class with a getAllUsers() method4. Test that you can sout all users from a user table (if you dont have

one maybe you can use a customer table or something like it)5. In a try-catch-fnally block: catch SqlException and throw a new

CustomException out of the method instead.6. Call the mapper method from your servlet and print the error

message to console (sout)

Page 23: Subject: Errorhandling and logging

Section 3: Log and respond

Subjects:1: Implement the import java.util.logging.Logger2: Log to fle3: Respond to user

Page 24: Subject: Errorhandling and logging

Slide 1: User response● In the servlet we will catch all exceptions and deal with them

● By

1) Logging to a fle on the server and by

2) Writing to the response (or forwarding the request to a view.jsp

Page 25: Subject: Errorhandling and logging

Slide 2: Logging1. Create an instance of the logger: private static fnal Logger logger =

Logger.getLogger(LoggingExamples.class.getName());

2. create a formatter see demo project create a handler: FileHandler handler = new FileHandler("loggingDemo-log.%u.%g.txt");

3. set formatter on handler: handler.setFormatter(new VerySimpleFormatter());

4. Add handler(s) to logger: logger.addHandler(handler);

5. Use the loggers log() method to send a message to the logger (often done inside a catch block):catch (Exception e) { logger.log(Level.SEVERE, "Error doing something", e);}

Page 26: Subject: Errorhandling and logging

Slide 3: User response1. In the servlet we catch the exceptions and forward the request to an error page2. Show a demo

Page 27: Subject: Errorhandling and logging

Exercise 3: Log and respond1. In your exercise project in the servlet in the method where you called

the data mapper do this

1. Catch the custom exception and in the catch block

1. Set an attribute on the request called “error”. This should contain the message text about what the error was.

2. Forward the request with request.getRequestDispatcher(“errorpage.jsp”).forward(request, response);

3. Create the errorpage.jsp to print a message from request.getAttribute(“error”,”some error message here”

2. Implenent a logger and log the error message to a fle. Check that the fle with the error message is there.

3. Deploy your project to your Digital Ocean server and check that you can provoke the error logging and that the fle is there.