shelf_exception_response 0.1.1+1

  • README.md
  • CHANGELOG.md
  • Installing
  • Versions
  • 46

Shelf Exception Response

Shelf middleware for easily creating shelf.Responses by simply throwing an HttpException.

What problem does it solve

When creating web service you have to handle a lot of http responses simply informing the client about a server-side error. Not all of those situations occure withing your request handlers but rather in some service classes or elsewhere in your application. In your controller you would write something like:

// given a simple function that throws in certain conditions
String doJob() {
	if(!myCondition) {
		throw new MyError();
	}
	return "Successfully done Job";
}

// code in the request handler
try {
	String res = doJob();
	return new shelf.Response.ok(res);
} on MyError {
	return new shelf.Response.forbidden("You have to be logged in");
}

When using HttpExceptions and the exception response middleware your controller could be simplified to the following:

// given a simple function that throws HttpException in certain conditions
String doJob() {
	if(!myCondition) {
		throw new ForbiddenException();
	}
	return "Successfully done Job";
}

// code in request handler
String res = doJob();
return new shelf.Response.ok(res);

The thrown HttpException will be handled and an appropriate shelf.Response will be generated. The response will have a correct Http status (eg.: 403), and the response body will be encoded in an acceptable format (Json, Xml, Text) using Tentacle Response Formatter.

Example

import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
import '../lib/exception_response.dart';

// a simple shelf server with exception response enabled.
void main() {

  var handler = const shelf.Pipeline()
    // add exception response middleware to the pipeline
    .addMiddleware(exceptionResponse())
    .addHandler((shelf.Request request){
      // handler can now throw HttpException that is handled a formatted.
      throw new NotFoundException({"something":["additional", 4, true]}, "This will show in the message");
    });

  io.serve(handler, 'localhost', 8080).then((server) {
    print('Serving at http://${server.address.host}:${server.port}');
  });
}

Adding additional response data for the body

Every HttpException can take a data parameter that accepts a Map<String, dynamic> data in the constructor that provides you with the ability to add custom data to the generated response. The fields status and message are always added to the response data but can be overridden by data. The message field can now receive additional text which will be appended to the HTTP Status Name (e.g.: Not Acceptable: Your text here) via the Exceptions details param.

Please keep in mind that responses of type "text/plain" do currently not output any data other than status and message (how should I format them anyhow ?). To add support for your own output format or change an existing one look at Tentacle Response Formatter under the section "Add your own response formatter".

// adding custom data and error details to response
throw new NotAcceptableException({
	"validation_errors": {
		"username": "to_long",
		"password": "not_contains_special_characters"
	},
	"Validation failed"
});

Add your own exception types

There are already predefined exceptions for the most common Http error code available but you may find that there is a specific error code missing. In that case you can simply define your own HttpException type by extending or implementing HttpException.

// creating custom exception
class IamATeapotException extends HttpException {
  final int status = 418;
  final String message = "I'm a teapot";
  final Map<String, dynamic> data;
  const IamATeapotException([this.data]);
}

License

Apache 2.0

0.1.1+1

  • support for shelf version <0.7.0
  • switch tentacle_response_formatter to shelf_response_formatter as latter supports shelf >=0.6.0
  • deprecated unittest package replaced with test package

0.1.1

  • added optional detail argument to exception constructors to allow additional information to be added the the message

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  shelf_exception_response: "^0.1.1+1"

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


      import 'package:shelf_exception_response/exception.dart';

      import 'package:shelf_exception_response/exception_response.dart';
  
Version Uploaded Documentation Archive
0.1.1+1 Jul 17, 2017 Go to the documentation of shelf_exception_response 0.1.1+1 Download shelf_exception_response 0.1.1+1 archive
0.1.1 Nov 5, 2014 Go to the documentation of shelf_exception_response 0.1.1 Download shelf_exception_response 0.1.1 archive
0.1.0 Apr 17, 2014 Go to the documentation of shelf_exception_response 0.1.0 Download shelf_exception_response 0.1.0 archive

Analysis

We analyzed this package on Jul 13, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0-dev.63.0
  • pana: 0.11.3

Scores

Popularity:
Describes how popular the package is relative to other packages. [more]
0 / 100
Health:
Code health derived from static analysis. [more]
85 / 100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100 / 100
Overall score:
Weighted score of the above. [more]
46
Learn more about scoring.

Platforms

Detected platforms: Flutter, other

Platform components identified in package: io.

Suggestions

  • Fix analysis and formatting issues.

    Analysis or formatting checks reported 17 hints.

    Run dartfmt to format lib/exception.dart.

    Run dartfmt to format lib/exception_response.dart.

  • Package is pre-v1 release.

    While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction API.

  • The description is too long.

    Search engines will display only the first part of the description. Try to keep it under 180 characters.

  • Maintain an example.

    None of the files in your example/ directory matches a known example patterns. Common file name patterns include: main.dart, example.dart or you could also use shelf_exception_response.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.3.0
shelf >=0.5.0+1 <0.7.0 0.6.8 0.7.3+2
shelf_response_formatter >=0.1.0 <0.2.0 0.1.0
Transitive dependencies
async 1.13.3 2.0.7
charcode 1.1.2
collection 1.14.10
http_parser 3.1.2
matcher 0.12.3
path 1.6.1
petitparser 1.7.6
source_span 1.4.0
stack_trace 1.9.2
stream_channel 1.6.7+1
string_scanner 1.0.2
typed_data 1.1.5
xml 2.6.0 3.0.0
Dev dependencies
test any