controller中处理异常的方式
- 常见的 Spring exceptions 异常自动转化成对应的http code
-
@ResponseStatus
定义异常时指定返回的http code -
@ExceptionHandler
指定异常类型调用的方法 -
@ControllerAdvice
处理所有controller的异常
spring exceptions 异常自动转化
- 一般不用,可以忽略
Spring exception | HTTP status code |
---|---|
BindException | 400 - Bad Request |
ConversionNotSupportedException | 500 - Internal Server Error |
HttpMediaTypeNotAcceptableException | 406 - Not Acceptable |
HttpMediaTypeNotSupportedException | 415 - Unsupported Media Type |
HttpMessageNotReadableException | 400 - Bad Request |
HttpMessageNotWritableException | 500 - Internal Server Error |
HttpRequestMethodNotSupportedException | 405 - Method Not Allowed |
MethodArgumentNotValidException | 400 - Bad Request |
MissingServletRequestParameterException | 400 - Bad Request |
MissingServletRequestPartException | 400 - Bad Request |
NoSuchRequestHandlingMethodException | 404 - Not Found |
TypeMismatchException | 400 - Bad Request |
- 使用姿势:在controller中抛出错误,下面的日子返回500 错误
package spittr.web;
// 定义异常类型
public class SpittleNotFoundException extends RuntimeException {
}
@RequestMapping(value="/{spittleId}", method=RequestMethod.GET)
public String spittle(
@PathVariable("spittleId") long spittleId,
Model model) {
Spittle spittle = spittleRepository.findOne(spittleId);
if (spittle == null) {
throw new SpittleNotFoundException();
}
model.addAttribute(spittle);
return "spittle";
}
@ResponseStatus
在定义异常时,指定返回的http code
package spittr.web;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value=HttpStatus.NOT_FOUND,
reason="Spittle Not Found")
public class SpittleNotFoundException extends RuntimeException {
}
@ExceptionHandler
处理指定的异常类型
@ExceptionHandler(DuplicateSpittleException.class)
public String handleDuplicateSpittle() {
return "error/duplicate";
}
@ControllerAdvice
处理所有controller的异常
-
@ControllerAdvice
也是@Conponent
会被spring加载 - 处理的方法,实现跟
@RequestMapping
处理相同
package spitter.web;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class AppWideExceptionHandler {
@ExceptionHandler(DuplicateSpittleException.class)
public String duplicateSpittleHandler() {
return "error/duplicate";
}
}
网友评论