B
B
bit_rainbow2015-02-19 13:40:22
Java
bit_rainbow, 2015-02-19 13:40:22

How do you handle errors in your resources?

Here is a typical resource code (JAR-RS) in a project:

@Path("authenticate")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response authenticate(Credentials credentials) {
  try{
     // some logic
  } catch (Exception1 e) { 
            //   etc  LOGGER.error(e);
            //   return Response.status(Status.UN_AUTHORIZED).build();
   } catch (Exception2 e) { 
            //   etc  LOGGER.error(e);
            //   return Response.status(Status.CAN_NOT_CREATE_TOKEN).build();
   }  catch (Exception3 e) { 
         //   etc  LOGGER.error(e);
         //   return Response.status(Status.SOME_OTHER_ERROR).build();
   }

  
  // return good stuff
}

The code is working, but not beautiful. I googled how to reduce the number of catch without damage - I didn’t find it, I rummaged through the rest book, I didn’t find it either. Anyone who has experienced this before can share their experience? I want to reduce the number of catches without harm, because in some places there are 10 catches.
More or less useful find

Answer the question

In order to leave comments, you need to log in

6 answer(s)
O
one pavel, 2015-02-19
@onepavel

1. Catch an error if you can handle it. Otherwise, throw it out of the method
2. In java 7 catch you can combine catch(NullPointerException | ClassNotFindException)
3. Take the base class of the error to catch all catch(Exception)
This amount of catch is normal, especially when working with http.

D
DigitalSmile, 2015-02-19
@DigitalSmile

If you use Jersey, then you can like this https://jersey.java.net/documentation/latest/repre...
If not, I advise you to try :)

V
Victor Gogilchin, 2015-02-19
@lslayer

In this particular case, I would make some kind of auxiliary class that returns the desired status depending on the error class.
for example

public static Status getStatus(Exception e) {
        if (e.getClass.equals(MyCoolUnautorisedException.class)) {
           return Status.UN_AUTHORIZED;
        }
        // More Exception handlers
     return null; //If something gone wrong
     }
  //Main code
    try {
       // some logic
    } catch (Exception e) { 
              //   etc  LOGGER.error(e);
              return Response.status(SomeStatusHandler.getStatus(e)).build();
    } finally {
        //Here we go!
    }

I
Igor Kalashnikov, 2015-02-19
@zo0m

Another "exotic" option, you can make an
Exception => Status map
, or more generic, like Exception => Handler
and collapse all the catches into a simple map call. Something like this.
With a map it is convenient if you have a lot of typical handlers.

Y
YV, 2015-02-26
@targetjump

Most rest frameworks provide the ability to write custom ExceptionMappers.

D
doublench21, 2017-10-29
@daminik00

Swift 4 Xcode 9.0

import Foundation

// Дополним String для простоты работы с NSRegularExpression
extension String {
    // Вычислимое св-во, которое возвращает NSRange строки String
    var toNSRange: NSRange { return NSMakeRange(0, self.utf16.count) }

    // Метод возвращающий String по заданному NSRange
    func substringFromNSRange(with nsrange: NSRange) -> String? {
        guard let range = Range(nsrange) else { return nil }
        let start = String.UTF16Index(encodedOffset: range.lowerBound)
        let end = String.UTF16Index(encodedOffset: range.upperBound)
        return String(self.utf16[start..<end])
    }
}

var htmlContext = "products_and_categories(123123)]}"
let regExp = try? NSRegularExpression(pattern: "products_and_categories(.*?)\\]\\}")
let matches = regExp?.matches(in: htmlContext, range: htmlContext.toNSRange)
for match in matches! {
    print(htmlContext.substringFromNSRange(with: match.range)!)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question