Not Found

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Java builder for error messages

License

exasol/error-reporting-java

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This project contains a Java-Builder for Exasol error messages. The invocations of the Builder can be parsed by the error-code-crawler-maven-plugin.

ExaError.messageBuilder("E-TEST-1").message("Something went wrong.").toString();

Result: E-TEST-1: Something went wrong.

You can specify placeholders in the message and replace them with parameters values, as follows:

ExaError.messageBuilder("E-TEST-2") .message("Unknown input: >.") .parameter("input", "unknown", "The illegal user input.").toString();
E-TEST-2: Unknown input: 'unknown'.` 

The optional third parameter for parameter(placeholder, value, description) is used by the error-code-crawler-maven-plugin to generate a parameter description.

Читайте также:  Метод сложения числа java

From version 0.3.0 on you can achieve the same result by specifying the parameter values directly in the message() method. This is a convenience variant that is a little more compact, but lacks the chance to describe the parameter.

ExaError.messageBuilder("E-TEST-2") .message("Message with > and >.", "first value", "second value").toString();
E-TEST-2: Message with 'q-value' and uq-value. 

When replacing placeholders in messages, ExaError quotes the values according to your choices. If you don’t specify a quoting option in a placeholder, you get auto-quoting. In this mode values are quoted depending on their type.

Type Quoted with Example Since version
String single quotes ‘Hello world!’
Character / char single quotes ‘A’
Path single quotes ‘/etc/cron.d’ 1.0.0
File single quotes ‘~/.bashrc’ 1.0.0
URI single quotes ‘URN:ISBN:0-330-28700-1’ 1.0.0
URL single quotes ‘https://example.org’ 1.0.0
null values pointy brackets
everything else not quoted 42 , 3.1415 , true

If you need a different quoting style, you can add switches to the placeholder definition:

If multiple conflicting switches are given, the one with the highest precedence (see list above) is taken.

Switches are separated with a pipe symbol | from the parameter name.

ExaError.messageBuilder("E-TEST-2") .message("Unknown input: <>.") .parameter("input", "unknown", "The illegal user input.").toString();
E-TEST-2: Unknown input: unknown. 

The mitigations describe actions the user can take to resolve the error. Here is an example of a mitigation definition:

ExaError.messageBuilder("E-TEST-2") .message("Not enough space on device.") .mitigation("Delete something.") .toString();
E-TEST-2: Not enough space on device. Delete something. 

You can use parameters in mitigations too.

ExaError.messageBuilder("E-TEST-2") .message("Not enough space on device >.") .mitigation("Delete something from >.") .parameter("device", "/dev/sda1", "name of the device") .toString();
E-TEST-2: Not enough space on device '/dev/sda1'. Delete something from '/dev/sda1'.` 

You can chain mitigation definitions if you want to tell the users that there is more than one solution.

ExaError.messageBuilder("E-TEST-2") .message("Not enough space on device.") .mitigation("Delete something.") .mitigation("Create larger partition.") .toString();
E-TEST-2: Not enough space on device. Known mitigations: * Delete something. * Create larger partition. 

Never Change the Meaning of an Error

If you have an error that does not fit anymore or was wrong to begin with, don’t reuse the error code. Instead, remove the old one and create a new one with a new code.

What you can do is fix typos in error, improve the readability or make them more detailed. But you should never change the meaning of an existing error.

Removing Obsolete Error Codes

In order to ensure a linear history of the error codes, developers should not reuse old error codes.

So when you plan to remove an obsolete error code:

  1. Remove it from the implementation
  2. Leave the highest-index in the error_code_config.yml untouched. Even if you deleted the entry with the highest number. The whole purpose of that index is to help avoid reusing error codes.
  3. Do not reuse the error code (see «Never Change the Meaning of an Error»).

Information for Developers

Источник

Show error messages java

Файл web.xml позволяет указать, какие страницы html или jsp будут отправляться пользователю при отправке статусных кодов ошибок. Для этого в web.xml применяется элемент .

Внутри этого элемента с помощью элемента указывается статусный код ошибки, который надо обработать. А элемент указывает на путь к странице html или jsp, которая будет отправляться пользователю.

Например, добавим в проект в папку WebContent новый файл 404.html со следующим кодом:

      

Resource not found!

error page in Java EE

В файле web.xml определим следующее содержимое:

В данном случае элемент error-code указывает, что мы будем обрабатывать ошибки со статусным кодом 404 (то есть такие ошибки, которые подразумевают отсутствие ресурса на сервере). А элемент location указывает, что в случае обращения к несуществующему ресурсу пользователю будет отправляться страница 404.html.

errors in web.xml in Java EE

Обработка исключений

Кроме настройки обработки стандартных ошибок протокола http,типа 404 или 403, файл web.xml позволяет настроить обработку исключений, которые могут возникнуть при обработке запроса. Для этого в web.xml применяется элемент

Например, добавим в проект в папку WebContent новый файл error.jsp и определим в нем следующий код:

       

Exception occurred while processing the request

Type:

Message:

Данная страница jsp будет отображать информацию об исключении. Через глобальный объект pageContext в страницу передается контекст. Если при обработке запроса возникло какое-нибудь исключение, то метод pageContext.getException() возвратит это исключение в виде объекта Exception. И далее мы можем исследовать этот объект и вызывать его методы, например, получить тип исключения и сообщение об исключении.

Симитируем с сервлете какое-нибудь исключение:

import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/hello") public class HelloServlet extends HttpServlet < protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < int x = 0; int y = 8 / x; >>

В данном случае мы получаем ошибку деления на нуль, которая представлена типом java.lang.ArithmeticException.

Теперь определим следующий файл web.xml:

   java.lang.Throwable /error.jsp   

Элемент exception-type указывает, что обрабатываться будут исключения типа java.lang.Throwable. Поскольку это базовый класс для всех типов исключений, то фактически мы будем обрабатывать все исключения. Хотя можно конкретизировать тип исключения, например, указать тот же java.lang.ArithmeticException.

Элемент location определяет страницу, которая отправляется пользователю при возникновении исключении. В данном случае это error.jsp.

В итоге при обращении к сервлету будет сгенерировано исключение, и мы увидим информацию о нем:

Источник

Оцените статью