通过ajax调用从弹簧控制器返回错误

时间:2017-07-19 15:20:47

标签: ajax spring spring-mvc

我正在尝试开发涉及体育的春季启动应用程序,我无法看到如何在错误部分中的ajax调用之后返回我的错误而不是成功,我想知道如何恢复来自控制器的所有返回错误部分中的类错误,而不是成功部分

N.B:此代码中的一切正常,只有成功部分才会返回错误。

类错误:

public class Error extends Exception{    
    public String code;    
    public String message;
}

课堂运动:

public class Sport {

    public String id;

    public String name;
}

Ajax Call

$.ajax({
    type : "GET",
    url : "/sports-actions",
    data: {"id" : sportId},
    contentType: "application/json",
    dataType : 'json',
    success: function (result) {       
           console.log(result);                
    },
    error: function (e) {
        console.log(e);
    }
}) 

Spring Controller

@RestController
@RequestMapping("/sports-actions")
public class SportController {  

    @RequestMapping(method = RequestMethod.GET)
    public Object deleteSport(@RequestParam("id") String id) {
        return new Error(404, "id is not valid");
    }
}

修改

我从Exception扩展了我的Error类,但是我做错了

throw new Error(400 ,"id is not valid") //我得到了不兼容的类型...

2 个答案:

答案 0 :(得分:3)

您可以执行以下测试:

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Object> deleteSport(@RequestParam("id") String id) {
    if({if id exists}) {
        return new ResponseEntity<Object>({your response object}, HttpStatus.OK);
    } else {
        //If the id doesn't exist.
        return new ResponseEntity<Error>(new Error(),HttpStatus.BAD_REQUEST);
    }
}

最佳实践

您应该使用@ControllerAdvice在方法级别使用@ExceptionHandler处理异常。

@ControllerAdvice
public class RestControllerAdvice {
    @ExeptionHandler(NotFoundException.class)
    public ResponseEntity<Error> handleNotFound(NotFoundException nfe) {
        //LOG error
        Error error = new Error();
        error.setCode(HttpStatus.NOT_FOUND);
        error.setMessage("ID not found OR Your custom message or e.getMessage()");
        return new ResponseEntity<Error>(error, HttpStatus.NOT_FOUND);
    }
}

您的控制器方法

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Object> deleteSport(@RequestParam("id") String id) {

    if({if id exists}) {
        return new ResponseEntity<Object>({your response object}, HttpStatus.OK);
    } else {
        throw new NotFoundException("Id not found");
    }
}

如果在请求处理期间抛出NotFoundException,则会调用上面的ControllerAdivce方法。您始终可以自定义错误。

答案 1 :(得分:1)

您当前的SportController实施将返回HTTP状态200,该状态永远不会进入error: function (e) {。您需要从控制器抛出异常才能进入错误块。

@RestController
@RequestMapping("/sports-actions")
public class SportController {  

    @RequestMapping(method = RequestMethod.GET)
    public Object deleteSport(@RequestParam("id") String id) throws Error {
        throw new Error("Test exception block");
    }
}
相关问题