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

Dav*_*gar 0 ajax spring spring-mvc

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

注意:此代码中一切正常,仅在成功部分返回错误。

类错误:

public class Error extends Exception{    
    public String code;    
    public String message;
}
Run Code Online (Sandbox Code Playgroud)

运动类别:

public class Sport {

    public String id;

    public String name;
}
Run Code Online (Sandbox Code Playgroud)

阿贾克斯调用

$.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);
    }
}) 
Run Code Online (Sandbox Code Playgroud)

弹簧控制器

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

我从 Exception 扩展了 Error 类,但执行此操作时出错

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

Ros*_*ion 5

您可以出于测试目的执行以下操作:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

最佳实践

您应该使用方法级别@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

你的控制器方法

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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